学习笔记之自动发邮件功能

我们自动化脚本运行完成之后生成了测试报告,如果将结果自动的发到邮箱就不用每次打开阅读,而是随着脚本的不断运行,生成的报告会越来越多,找到最近得报告也是一个比较麻烦的事情,所以能自动的将结果发到boss邮箱,也是不错的选择。
python的smtplib模块提供了一种很方便的途径发送电子邮件,它对smtp协议进行了简单的封装。
smtp协议的基本命令包括:
HELO 向服务器标识用户身份
MAIL 初始化邮件传输mail from:
RCPT 标识单个的的邮件接收人;常在MAIL命令后面,可有多个rcpt to:
DATA 在单个或多个RCPT命令后,表示所有的邮件接收人已标识,并初始化数据传输,以.结束
VRFY 用于验证指定的用户/邮箱是否存在;由于安全方面的原因,服务器常禁止此命令
EXPN 验证给定的邮箱列表是否存在,扩充邮箱列表,也常被禁用
HELP 查询服务器支持什么命令
NOOP 无操作,服务器响应OK
QUIT 结束会话
RCPT TO 指明的接收者地址
一般smtp会话两种方式,一种是邮件直接投递,另一种是验证后的发信
使用以下代码可以查看SMTP中的方法:

from smtplib import SMTP
help(SMTP)

发送HTML格式的邮件


from smtplib import SMTP
from email.mime.text import MIMEText
from email.header import Header
#发送邮箱服务器
smtpserver = 'smtp.QQ.com'
smtpserver.encode('utf-8')
#发送用户名和密码
user = '526*****@qq.com'
password='ztrngz*****'#授权码
#发送邮箱
sender = '526*****@qq.com'
#接收邮箱
receiver = '[email protected]'
#发送邮箱主题
subject='python email test'
#编写HTML类型的邮件正文
msg = MIMEText('<HTML><h1>你好</h></html>','html','utf-8')
msg['subject']=Header(subject,'utf-8')
#链接发送邮件
smtp = SMTP()
smtp.connect(smtpserver)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()

发送成功后:
在这里插入图片描述

带附件的方式发送邮件

#发送带附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
#发送邮件服务器
smtpserver = 'smtp.QQ.com'
smtpserver.encode('utf-8')
#发送用户名和密码
user = '526*****@qq.com'
password='ztrng*******'
#发送邮箱
sender = '526****@qq.com'
#接收邮箱
receiver = '[email protected]'
#发送邮箱主题
subject='python send email test'
#发送附件
sendfile= open('F:\\**\\PycharmProjects\\untitled\\HTMLTestBaidu\\sendmail\\log.txt','rb').read()

att = MIMEText(sendfile,'base64','utf-8') #指定编码类型
att["Content-Type"]='application/octet-stream'
att["Content-Disposition"] = 'attachment;filename="log.txt"'#附件显示的文件名

msgRoot=MIMEMultipart('related')
msgRoot['Subject']=subject
msgRoot.attach(att)
#链接发送邮件
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(user,password)
smtp.sendmail(sender,receiver,msgRoot.as_string())
smtp.quit()

发送成功后:
在这里插入图片描述
打开后:
在这里插入图片描述
如果接收人是多个的话,可以把接收人设置成一个数组,进行发送

receiver = ['[email protected]','[email protected]','[email protected]']

如果要发送测试报告最新的log:

1.为每个报告加上时间,这样不会重复(返回上一篇)
2.需要扩展
import os
#定义文件目录
result_dir = '文件路径'
lists = os.listdir(result_dir)
#打印所有文件名列表
for i in lists:
    print(i)
#重新按时间对目录下的文件进行排序/对数组进行排序
lists.sort(key=lambda fn: os.path.getmtime(result_dir+'\\'+fn)
print("==========================================")
#打印排序后的文件名列表
for i in lists:
    print(i)
print(('最新的文件为:'+lists[-1]))
file = os.path.join(result_dir,lists[-1])
print(file)

lambda fn: 匿名函数,冒号左右都需要入参

aa = lambda a,b:a+b
print(aa(2,5)
>>>>> 7

排序前和排序后的打印结果:
在这里插入图片描述
找到最新的文件,显示出来:
在这里插入图片描述

发布了24 篇原创文章 · 获赞 0 · 访问量 553

猜你喜欢

转载自blog.csdn.net/MoLi_D/article/details/104279167
今日推荐