自动化测试框架中,一般都会在执行失败后给测试人员发送失败通知。常见通知方式:邮件通知、企业微信通知、钉钉通知等, 邮件通知是最为普遍的一种最正式规范的通知方式。
这次我们就聊聊Python中如何发送邮件通知,我们都知道Python内置了对SMTP的支持,可以发送纯文本、富文本、HTML 等格式的邮件,但是SMTP在编写代码中稍有点复杂。
所以希望能有一个轻量级的解决方案,直到遇见了yagmail。
以163邮箱为例,在编码之前,我们需要开启SMTP服务。
手动增加一个授权码。账号、授权码、服务器地址用于连接登录邮箱服务器。
在Python里发邮件,yagmail大概是目前最简单易用的方式。yagmail 只需要几行代码,就能实现发送邮件的功能。相比 zmail,yagmail 实现发送邮件的方式更加简洁优雅。
github: https://github.com/kootenpv/yagmail
同时支持python2和python3两个版本安装
pip install yagmail
pip3 install yagmail
主要介绍发送文本和发送附件两种常用的载体。
先简单的发送一段文本,contents为list结构实现文本换行。
代码例子:
import yagmail
# 连接服务器
# 用户名、授权码、服务器地址
yag = yagmail.SMTP(user='xxx@163.com', password='授权码', host='smtp.163.com')
#接着,通过 send() 函数,将邮件发送出去
contents = ['This is the body, and here is just text http://somedomain/image.png',
'You can find an audio file attached.', '/local/path/song.mp3']
yag.send('xxxx@163.com', 'subject', contents)
# 关闭连接
yag_server.close()
可以在接收端的邮件列表看到刚才代码执行发送邮件,收到邮件基本没有延迟。
如下代码是从本地加载多个测试报告作为附件发送
代码例子:
import yagmail
# 连接服务器
# 用户名、授权码、服务器地址
yag = yagmail.SMTP(user='xxx@163.com', password='授权码', host='smtp.163.com')
#接着,通过 send() 函数,将邮件发送出去
# 发送对象列表
email_to = ['xxxx@163.com', ]
email_title = '测试报告'
email_content = "这是测试报告的具体内容"
# 附件列表
email_attachments = ['./report-1652541422.html','./reports/report-1652540875.html']
# 发送邮件
yag.send(email_to, email_title, email_content, email_attachments)
# 关闭连接
yag_server.close()
在邮件的附件中可以看到两个测试报告,点开是可以预览的。
上面介绍了Python中使用ymail发送邮件的一些基本使用,并且在我日常工作过程中也经常被用到,极力推荐大家使用。