本文介绍如何通过smtp模块实现邮件的抄送和密送功能。
在发送邮件时,除了发送给相关的责任人,有时还需要知会某些人。这时就需要在邮件里指定抄送人员列表。相关实现如下:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os
FROMADDR = "myaddr@server.com"
PASSWORD = 'foo'
TOADDR = ['toaddr1@server.com', 'toaddr2@server.com']
CCADDR = ['ccaddr1@server.com', 'ccaddr2@server.com']
# 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)功能,和上面介绍的抄送功能类似。参考代码实现:
oaddr = 'buffy@sunnydale.k12.ca.us'
cc = ['alexander@sunydale.k12.ca.us','willow@sunnydale.k12.ca.us']
bcc = ['chairman@slayerscouncil.uk']
fromaddr = 'giles@sunnydale.k12.ca.us'
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必须是所有接收者的列表。