本文實例講述了Python發送郵件測試報告操作。分享給大家供大家參考,具體如下:
發郵件需要用到python兩個模塊,smtplib和email,這倆模塊是python自帶的,只需import即可使用。smtplib模塊主要負責發送郵件,email模塊主要負責構造郵件。其中MIMEText()定義郵件正文,Header()定義郵件標題。MIMEMulipart模塊構造帶附件
發送HTML格式的郵件:
send_email_html.py
import smtplibfrom email.mime.text import MIMEText #MIMEText()定義郵件正文from email.header import Header #Header()定義郵件標題#發送郵箱服務器smtpserver = 'smtp.sina.com'#發送郵箱用戶/密碼(登錄郵箱操作)user = "username@sina.com"password = "password"#發送郵箱sender = "username@sina.com"#接收郵箱receiver = "8888@qq.com"#發送主題subject = 'email by python'#編寫HTML類型的郵件正文(把HTML代碼寫進入)msg = MIMEText('<html><body><a href="">百度一下</a></p></body></html>','html','utf-8')msg['Subject'] = Header(subject,'utf-8')#連接發送郵件(smtplib模塊基本使用格式)smtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(user,password)smtp.sendmail(sender,receiver,msg.as_string())smtp.quit()說明:
smtplib.SMTP():實例化SMTP()
connect(host,port):
host:指定連接的郵箱服務器。
port:指定連接服務器的端口號,默認為25.
login(user,password):user:登錄郵箱的用戶名。password:登錄郵箱的密碼。
sendmail(from_addr,to_addrs,msg,...):
from_addr:郵件發送者地址
to_addrs:郵件接收者地址。字符串列表['接收地址1','接收地址2','接收地址3',...]或'接收地址'
msg:發送消息:郵件內容。一般是msg.as_string(),as_string()是將msg(MIMEText對象或者MIMEMultipart對象)變為str。
quit():用于結束SMTP會話。
發送帶附件的郵件
send_email_file.py
import smtplibfrom email.mime.text import MIMEText #MIMRText()定義郵件正文from email.mime.multipart import MIMEMultipart #MIMEMulipart模塊構造帶附件#發送郵件的服務器smtpserver = 'smtp.sina.com'#發送郵件用戶和密碼user ="xxx@sina.com"password = "xxx"#發送者sender = "xxx@sina.com"#接收者receiver = "1xxx@qq.com"#郵件主題subject = "附件的郵件"#發送附件sendfile = open("C://Users//Administrator//Desktop//html5.txt","r").read()att = MIMEText(sendfile,"base64","utf-8")att["Content-Type"] = "application/octet-stream"att["Content-Disposition"] = "attachment;filename = 'html5.txt'"msgRoot = MIMEMultipart('related')msgRoot['Subject'] = subjectmsgRoot.attach(att)smtp = smtplib.SMTP()smtp.connect(smtpserver)smtp.login(user,password)smtp.sendmail(sender,receiver,msgRoot.as_string())smtp.quit()
查找最新的測試報告
find_file.py
import os#定義文件目錄result_dir = "E://自動化測試項目//子項目_bbs//report"lists = os.listdir(result_dir) #獲取該目錄下的所有文件、文件夾,保存為列表#對目錄下的文件按創建的時間進行排序lists.sort(key=lambda fn: os.path.getmtime(result_dir + "//" + fn))#lists[-1]取到的是最新生成的文件或文件夾print(('最新的文件是:' + lists[-1]))file = os.path.join(result_dir,lists[-1])print(file)
整合自動化測試發送測試報告郵件
from HTMLTestRunner import HTMLTestRunnerfrom email.mime.text import MIMETextfrom email.header import Headerimport smtplibimport unittestimport timeimport os#==============定義發送郵件==========def send_mail(file_new): f = open(file_new,'rb') mail_body = f.read() f.close() msg = MIMEText(mail_body,'html','utf-8') msg['Subject'] = Header("自動化測試報告",'utf-8') smtp = smtplib.SMTP() smtp.connect('smtp.sina.com') #郵箱服務器 smtp.login("sender@sina.com","password") #登錄郵箱 smtp.sendmail("sender@sina.com","receiver@qq.com",msg.as_string()) #發送者和接收者 smtp.quit() print("郵件已發出!注意查收。")#======查找測試目錄,找到最新生成的測試報告文件======def new_report(test_report): lists = os.listdir(test_report) #列出目錄的下所有文件和文件夾保存到lists lists.sort(key=lambda fn:os.path.getmtime(test_report + "//" + fn))#按時間排序 file_new = os.path.join(test_report,lists[-1]) #獲取最新的文件保存到file_new print(file_new) return file_newif __name__ == "__main__": test_dir = "測試用例存放目錄" test_report = "測試報告存放目錄" discover = unittest.defaultTestLoader.discover(test_dir, pattern = 'test_*.py') now = time.strftime("%Y-%m-%d_%H-%M-%S") filename = test_report + '//' + now + 'result.html' fp = open(filename,'wb') runner = HTMLTestRunner(stream = fp, description = '用例執行情況:') runner.run(discover) fp.close() new_report = new_report(test_report) send_mail(new_report) #發送測試報告 1.通過unittest框架的discover()找到匹配的測試用例,由HTMLTestRunner的run()方法執行測試用例并生成最新的測試報告。
2.調用new_report()函數找到測試報告目錄下最新生成的測試報告,返回測試報告的路徑。
3.將得到的最新測試報告的完整路徑傳給send_mail()函數,實現發郵件功能。
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答