本文介绍如何封装一个自动发邮件测试报告功能系列
在此之前我们需要先学习【发送邮件带附件】的方法
层次架构如下:
新建一个send_email.py文件
代码如下:
import smtplib
import os.path
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#发送邮件
sender = 'xxxxxx@qq.com'
#接收邮件
receiver = 'xxxxxx@qq.com'
#发送邮件主题
subject = '自动化测试报告'
#发送邮件服务器
smtpserver = 'smtp.qq.com'
#发送邮件用户
username = 'xxxxxx@qq.com'
#发送邮件授权码
password = 'xxxxxxxxxxxxxxx'
#发送附件
file_path = os.path.dirname(os.path.abspath('.')) + '/report/xxx.html' #获取当前目录report文件下附件xxx.html为附件名称
sendfile = open(file_path, 'rb').read()
#编写邮件正文
att = MIMEText(sendfile, 'base64', 'utf-8') #引入附件
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = "attachment;filename='xxx.html'"
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot.attach(att)
#连接发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()
由于我准备的附件是HTMLRunner.html文件,成功发送的邮件如下图:
这一篇我们知道怎么发送带附件的邮件方法,那么在实际项目中,每次最新的测试报告生成,我们不可能都去修改上传附件地址。那就失去了自动化的意义了,有什么方法可以让代码找到最新的测试报告呢,下一篇我们就来介绍。