这里封装一个send_mail()方法,用于测试完成后读取测试报告内容,并将测试结果通过邮件发送到接收人
SMTP:Simple Mail Transfer Protocol,简单邮件传输协议
1 # coding: utf-8 2 3 import smtplib # 导入smtplib模块 4 from email.mime.text import MIMEText 5 from email.header import Header 6 from .logger import * 7 8 9 def send_email(test_report): 10 11 with open(test_report, 'r', encoding='utf-8') as f: 12 mail_body = f.read() # 打开测试报告,读取报告内容作为邮件内容 13 sender = '*********@***.com' # 发出邮箱 14 receiver = ['******@***.com', '*******@**.com'] # 接收邮箱 15 mail_server = 'smtp.139.com' # 邮箱服务地址,这里以139邮箱为例 16 subject = '自动化测试报告' # 邮件标题 17 username = '#########' # 邮箱登录名 18 passwd = '########' # 密码 19 message = MIMEText(mail_body, 'html', 'utf-8') # 设置邮件格式 20 message['Subject'] = Header(subject, charset='utf-8') 21 # 邮箱登录 22 smtp = smtplib.SMTP() # 实例化smtplib.SMTP()类对象 23 smtp.connect(mail_server) # 连接邮件服务器 24 smtp.login(username, passwd) # 登录 25 # 发送邮件 26 for i in receiver: 27 smtp.sendmail(sender, i, message.as_string()) 28 Logger().get_log().info( '邮箱:' + i + ',发送邮件成功!\n') # 打印log 29 smtp.quit()
调用此方法即可实现邮件发送
1 # coding: utf-8 2 # Team : Quality Management Center 3 # Author:Carson 4 # Date :2019/6/19 17:26 5 # Tool :PyCharm 6 7 from constant.path import * 8 import HTMLTestRunner 9 from encapsulation.add_case import * 10 from encapsulation.send_mail import * 11 12 # 设置测试报告参数 13 fp = open(report_path, "wb") 14 runner = HTMLTestRunner.HTMLTestRunner(stream=fp, 15 title=u'测试报告标题', 16 description=u'描述信息:', 17 tester=u'测试人员') 18 # run所有用例 19 runner.run(add_test()) 20 fp.close() 21 time.sleep(1) 22 print(u'测试报告生成地址:' + report_path) 23 time.sleep(5) 24 send_email(report_path)