使用python将最新的测试报告以附件的形式发到指定邮箱
Python  /  管理员 发布于 7年前   179
具体代码如下所示:
import smtplib, email, os, timefrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextfrom email.header import Header#设置smtplib所需的参数smtpserver = 'smtp.qq.com' #SMTP服务器地址username = '[email protected]' # 发件人地址,通过控制台创建的发件人地址password = '******' # 发件人密码,通过控制台创建的发件人密码receiver = ['[email protected]'] #单个收件人# receivers = ['[email protected]', '[email protected]'] # 收件人地址或是地址列表,支持多个收件人,最多30个# 构造邮件MIMEMultipart对象msg = MIMEMultipart('mixed')msg['Subject'] = Header('自动化测试报告' + time.strftime("%Y-%m-%d"), 'utf-8').encode()#自定义邮件主题msg['From'] = '%s <%s>' % (username, username)#邮件发送者msg['To'] = ";".join(receiver)#邮件接受者msg['Message-id'] = email.utils.make_msgid()msg['Date'] = email.utils.formatdate()# 构造文字内容text_plain = MIMEText('附件为接口自动化测试报告,请查收!', 'plain', 'utf-8')#邮件内容msg.attach(text_plain)#构造附件test_report = r'F:\PythonAutomation\Python_PyCharm\TestReport' #存放文件的目录lists = os.listdir(test_report) #列出目录的下所有文件保存到listslists.sort(key=lambda fn:os.path.getmtime(test_report + "\\" + fn)) #按时间排序file_new = os.path.join(test_report,lists[-1]) #获取最新的文件保存到file_newsendfile = open(file_new,'rb').read()text_att = MIMEText(sendfile, 'base64', 'utf-8')text_att["Content-Type"] = 'application/octet-stream'text_att["Content-Disposition"] = 'attachment; filename="report.html"'#重新命名附件msg.attach(text_att)# 发送邮件try: # client = smtplib.SMTP() # client.connect(smtpserver, 25) #SMTP普通端口为25 client = smtplib.SMTP_SSL() #python 2.7以上版本,若需要可使用SSL client.connect(smtpserver, 465) #SSL端口465 # client.set_debuglevel(1) #用set_debuglevel(1)可以打印出和SMTP服务器交互的所有信息 client.login(username, password) client.sendmail(username, receiver, msg.as_string()) client.quit() print('邮件发送成功')except smtplib.SMTPConnectError as e: print('邮件发送失败,连接失败:', e.smtp_code, e.smtp_error)except smtplib.SMTPAuthenticationError as e: print('邮件发送失败,认证错误:', e.smtp_code, e.smtp_error)except smtplib.SMTPSenderRefused as e: print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error)except smtplib.SMTPRecipientsRefused as e: print('邮件发送失败,收件人被拒绝:', e.args, e.recipients)except smtplib.SMTPDataError as e: print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)except smtplib.SMTPException as e: print('邮件发送失败: ', str(e))except Exception as e: print('邮件发送失败: ', str(e))
执行结果如下:
总结
以上所述是小编给大家介绍的使用python将最新的测试报告以附件的形式发到指定邮箱,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号