前言:
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 = 'test1@163.com'
#receiver可設置多個,使用“,”分隔
receiver = 'wang@mobile.cn,zhang@mobile.cn,lily@mobile.cn'
username = 'test1@163.com'
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)
以上~~對你有幫助的話,點贊吧~👍