python调用smtp发送邮件(多个收件人)
from email import encoders
from email.mime.text import MIMEText
from email.utils import formatdate
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.header import Header
import smtplib
def send_email(file_name):
'''发送测试报告'''
try:
From = "send@xxx.com"
To = "recieved@xx.com,recieved2@xx.com"
source = '..//Report//' + file_name
server = smtplib.SMTP("smtp.xxx.com")
server.login("send@xxx.com","password") #仅smtp服务器需要验证时
# 构造MIMEMultipart对象做为根容器
main_msg = MIMEMultipart()
# 构造MIMEText对象做为邮件显示内容并附加到根容器
text_msg = MIMEText("xx自动化测试报告!")
main_msg.attach(text_msg)
# 构造MIMEBase对象做为文件附件内容并附加到根容器
contype = 'application/octet-stream'
maintype, subtype = contype.split('/', 1)
# 读入文件内容并格式化
data = open(source, 'rb')
file_msg = MIMEBase(maintype, subtype)
file_msg.set_payload(data.read( ))
data.close( )
encoders.encode_base64(file_msg)
# 设置附件头
basename = os.path.basename(source)
#解决中文附件名乱码问题
file_msg.add_header('Content-Disposition', 'attachment', filename=('gbk', '', basename))
main_msg.attach(file_msg)
# 设置根容器属性
main_msg['From'] = From
main_msg['To'] = To
main_msg['Subject'] = Header("XX自动化测试报告","utf-8")
main_msg['Date'] = formatdate( )
# 得到格式化后的完整文本
fullText = main_msg.as_string( )
# 用smtp发送邮件
try:
server.sendmail(From, To.split(','), fullText)
finally:
server.quit()
except Exception:
logger.exception('发送邮件出错!')
今天太阳也东升,而后西沉,早晨盛开的花儿也将凋谢;今天的太阳也西沉,而后东升,阳光照射之处遍地花开,但却已非昨日之花。