一下代碼是自己結合教材,並結合以往用到的實例編寫的代碼,可以做為參考
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from HTMLTestRunner import HTMLTestRunner from email.header import Header import unittest import time,os #==============定義發送郵件 =============== def send_mail(file_new): f = open(file_new,'rb') #讀取測試報告正文 mail_body = f.read() f.close() # 發送郵箱服務器 smtpserver = "smtp.163.com" # 發件人郵箱 sender = 'qwe_test@163.com' # 接收人郵箱 receiver = 'qwe@163.com' # 發送郵箱用戶信息 username = 'qwe@163.com' # 客戶端授權碼 password = 'qweqw18' #通過 模塊構造的帶附件的郵件如圖 msg = MIMEMultipart() #編寫html類型的郵件正文,MIMEtext()用於定義郵件正文 #發送正文 text = MIMEText(mail_body, 'html', 'utf-8') text['Subject'] = Header('自動化測試報告', 'utf-8') msg.attach(text) #發送附件 #Header()用於定義郵件標題 msg['Subject'] = Header('自動化測試報告', 'utf-8') msg_file = MIMEText(mail_body, 'html', 'utf-8') msg_file['Content-Type'] = 'application/octet-stream' msg_file["Content-Disposition"] = 'attachment; filename="TestReport.html"' msg.attach(msg_file) # 如果只發正文的話,上面的代碼 從password 下面到這段注釋上面 # 全部替換為下面的兩行代碼即可,上面的代碼是增加了發送附件的功能。 # text = MIMEText(mail_body, 'html', 'utf-8') # text['Subject'] = Header('自動化測試報告', 'utf-8') #連接發送郵件 # smtp = smtplib.SMTP() # smtp.connect(smtpserver) # smtp.login(username, password) # smtp.sendmail('qwet@163.com', 'qewq@163.com', msg.as_string()) # smtp.quit() # print("email has send out !") #一樣的邏輯,不一樣的寫法導致上面的發送失敗,下面這種發送成功,所以要使用msg['from']這種寫法 msg['from'] = 'qweqt@163.com' # 發送郵件的人 msg['to'] = 'q10@163.com' # smtp = smtplib.SMTP('smtp.163.com', 25) # 連接服務器 smtp = smtplib.SMTP() smtp.connect('smtp.163.com') smtp.login(username, password) # 登錄的用戶名和密碼 smtp.sendmail(msg['from'], msg['to'], msg.as_string()) # 發送郵件 smtp.quit() print('sendmail success') #======================查找最新的測試報告========================== def new_report(testreport): #方式1: # lists = os.listdir(testreport) # lists.sort(key = lambda fn: os.path.getmtime(testreport + '\\' + fn)) # file_new = os.path.join(testreport,lists[-1]) # print(file_new) # return file_new #方式2: dirs = os.listdir(testreport) dirs.sort() newreportname = dirs[-1] print('The new report name: {0}'.format(newreportname)) file_new = os.path.join(testreport, newreportname) return file_new if __name__ == '__main__': test_dir = os.path.join(os.getcwd(),'test_case') #test_report = "D:/SProgram/PySpace/wmq/SendHtmlMail/report" test_report = os.path.join(os.getcwd(), 'report') discover = unittest.defaultTestLoader.discover(test_dir,pattern='test*.py') now = time.strftime("%Y-%m-%d-%H_%M_%S") filename = test_report+'/result_'+now+'.html' fp = open(filename,'wb') runner = HTMLTestRunner(stream=fp,title="測試報告",description='用例執行情況:') runner.run(discover) fp.close() new_report = new_report(test_report) send_mail(new_report)