Python-SMTP傳送郵件(HTML、圖片、附件)
阿新 • • 發佈:2019-01-12
前言:
SMTP(Simple Mail Transfer Protocol)即簡單郵件傳輸協議,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。
一、Python傳送HTML郵件
# -*- coding: utf-8 -*- # @Time : 2018/6/6 上午11:27 # @Author : Wang # @File : test_mail_html.py import smtplib from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText def sendMail(): # 定義相關資料,請更換自己的真實資料 smtpserver = 'smtp.163.com' sender = '
[email protected]' #receiver可設定多個,使用“,”分隔 receiver = '[email protected],[email protected],[email protected]' username = '[email protected]' password = '2018' msg = MIMEMultipart() boby = """ <h3>Hi,all</h3> <p>附件為本次FM_自動化測試報告。</p> <p>請解壓zip,並使用Firefox開啟index.html檢視本次自動化測試報告結果。</p> """ mail_body = MIMEText(boby, _subtype='html', _charset='utf-8') msg['Subject'] = Header("Android_自動化測試報告", 'utf-8') msg['From'] = sender receivers = receiver toclause = receivers.split(',') msg['To'] = ",".join(toclause) print(msg['To']) msg.attach(mail_body) # 登陸併發送郵件 try: smtp = smtplib.SMTP() ##開啟除錯模式 # smtp.set_debuglevel(1) smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, toclause, msg.as_string()) except: print("郵件傳送失敗!!") else: print("郵件傳送成功") finally: smtp.quit()
二、Python傳送郵件帶附件
#新增report附件 att = MIMEText(open("/report/html.zip", "rb").read(), "base64", "utf-8") att["Content-Type"] = "application/octet-stream" times = time.strftime("%m_%d_%H_%M", time.localtime(time.time())) filename_report = 'FM_Android_Report'+'_'+times+'.zip' att["Content-Disposition"] = 'attachment; filename= %s ' %filename_report msg.attach(att)
三、Python傳送郵件正文帶圖片
msg = MIMEMultipart()
boby = """
<h3>Hi,all</h3>
<p>附件為本次FM_自動化測試報告。</p>
<p>請解壓zip,並使用Firefox開啟index.html檢視本次自動化測試報告結果。</p>
<p>
<br><img src="cid:image1"></br>
</p>
<p>
"""
msg.attach(mail_body)
fp = open("/image/1.png", 'rb')
images = MIMEImage(fp.read())
fp.close()
images.add_header('Content-ID', '<image1>')
msg.attach(images)
以上~~對你有幫助的話,點贊吧~