標籤:pytho 規則 user 團隊 需求 測試報告 file import repo
在自動化測試結束後,我們往往需求把測試結果通過郵件發送給團隊成員。Python語言如何?自動發送郵件?請看:
方式一:
SMTP(Simple Mail Transfer Protocol)即簡易郵件傳輸通訊協定,它是一組用於由源地址到目的地址傳送郵件的規則,由它來控制信件的中轉方式。
python的smtplib提供了一種很方便的途徑寄送電子郵件。它對smtp協議進行了簡單的封裝。
執行個體:import smtplib
from email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartclass SendEmail(): global send_user global smtpserver global password global sendfile # 發送郵箱伺服器 smtpserver = ‘smtp.163.com‘ # 發送郵箱/密碼 send_user = "###@163.com" password = ‘###‘ # 發送的附件 sendfile = open("附件路徑",‘rb‘).read() def send_email(self,receiver_list, sub): user = "coco"+"<"+send_user+">" att = MIMEText(sendfile,‘base64‘,‘utf-8‘) att[‘Content-Type‘] = ‘application/octet-stream‘ att[‘Content-Disposition‘] = ‘attachment;filename="report.html"‘ message = MIMEMultipart(‘related‘) message[‘Subject‘] = sub message.attach(att) message[‘From‘] = send_user message[‘To‘] = ";".join(receiver_list) server = smtplib.SMTP() server.connect(smtpserver) server.login(send_user, password) server.sendmail(send_user, receiver_list, message.as_string()) server.quit()if __name__ == "__main__": smtpsender = SendEmail() sub = "python測試報告" receiver_list = [‘[email protected]‘,‘[email protected]‘] smtpsender.send_email(receiver_list, sub)
方式二:yagmail 實現發郵件
yagmail 可以更簡單的來實現自動發郵件功能。
github項目地址: https://github.com/kootenpv/yagmail
先安裝yagmail 庫,在cmd命令環境下 :pip install yagmail
執行個體:
import yagmail# 連結郵箱伺服器yag = yagmail.SMTP(user="###@163.com",password="###",host="smtp.163.com")# 郵件發送內容content = "郵件內文,test......."# 發送郵件yag.send(receiver="###@163.com",subject="測試郵件",content)
發送給多人,用list存放收件者郵箱:
yag.send(["###@163.com","###@qq.com"],subject="測試郵件",content)
發送附件
yag.send("###@163.com",”subject",content,["附件路徑1","附件路徑2"])
Python發送郵件