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('發送郵件出錯!')