失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > Python + HTMLTestRunner + smtplib 完成测试报告生成及发送测试报告邮件

Python + HTMLTestRunner + smtplib 完成测试报告生成及发送测试报告邮件

时间:2020-10-17 19:02:06

相关推荐

Python + HTMLTestRunner + smtplib 完成测试报告生成及发送测试报告邮件

一下代码是自己结合教材,并结合以往用到的实例编写的代码,可以做为参考

import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom HTMLTestRunner import HTMLTestRunnerfrom email.header import Headerimport unittestimport time,os#==============定义发送邮件 ===============def send_mail(file_new):f = open(file_new,'rb')#读取测试报告正文mail_body = f.read()f.close()# 发送邮箱服务器smtpserver = ""# 发件人邮箱sender = 'qwe_test@'# 接收人邮箱receiver = 'qwe@'# 发送邮箱用户信息username = 'qwe@'# 客户端授权码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@', 'qewq@', msg.as_string())# smtp.quit()# print("email has send out !")#一样的逻辑,不一样的写法导致上面的发送失败,下面这种发送成功,所以要使用msg['from']这种写法msg['from'] = 'qweqt@' # 发送邮件的人msg['to'] = 'q10@'# smtp = smtplib.SMTP('', 25) # 连接服务器smtp = smtplib.SMTP()smtp.connect('')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_newif __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)

如果觉得《Python + HTMLTestRunner + smtplib 完成测试报告生成及发送测试报告邮件》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。