1. 程式人生 > >Python網路程式設計:E-mail服務(八) 實現抄送和密送功能

Python網路程式設計:E-mail服務(八) 實現抄送和密送功能

簡介

本文介紹如何通過smtp模組實現郵件的抄送和密送功能。

抄送功能實現

在傳送郵件時,除了傳送給相關的責任人,有時還需要知會某些人。這時就需要在郵件裡指定抄送人員列表。相關實現如下:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os

FROMADDR = "[email protected]"
PASSWORD = 'foo'

TOADDR = ['[email protected]', '[email protected]
'] CCADDR = ['[email protected]', '[email protected]'] # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = 'Test' msg['From'] = FROMADDR msg['To'] = ', '.join(TOADDR) msg['Cc'] = ', '.join(CCADDR) # Create the body of the message (an HTML version). text = """Hi this is the body """ # Record the MIME types of both parts - text/plain and text/html. body = MIMEText(text, 'plain') # Attach parts into message container. msg.attach(body) # Send the message via local SMTP server. s = smtplib.SMTP('server.com', 587) s.sendmail(FROMADDR, TOADDR + CCADDR, msg.as_string()) s.quit()
這裡需要注意的是,需要將所以傳送和抄送人員以列表的形式,傳送給sendmail(from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])函式的to_addrs引數。否則CC功能失效。

實現BCC功能

使用者如果需要實現密送(BCC)功能,和上面介紹的抄送功能類似。參考程式碼實現:
oaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '
[email protected]
' message_subject = "disturbance in sector 7" message_text = "Three are dead in an attack in the sewers below sector 7." message = "From: %s\r\n" % fromaddr + "To: %s\r\n" % toaddr + "CC: %s\r\n" % ",".join(cc) + "Subject: %s\r\n" % message_subject + "\r\n" + message_text toaddrs = [toaddr] + cc + bcc server = smtplib.SMTP('smtp.sunnydale.k12.ca.us') server.set_debuglevel(1) server.sendmail(fromaddr, toaddrs, message) server.quit()

總結

TO, CC, BCC僅在文字頭存在區別,在SMTP級別來看,TO, CC, BCC都是接收者。因此sendmail( )函式的to_addrs必須是所有接收者的列表。