Python+request+ smtplib 测试结果html报告邮件发送(下)《六》
目录结构如下:

1、cfg.ini的配置信息写法如下:
[email]
;--------------------------使用腾讯企业邮箱作为发件人的操作如下---------------------
smtp_server = smtp.qq.com
Port = 465
Sender = 请写你自己的QQ邮箱
psw = 请写你自己的QQ授权码
Receiver = 904199561@qq.com (注:请写你的邮件收件人邮箱)
2、readConfig.py 此文件主要是获取cfg.ini中对应的配置信息
#!/usr/bin/env python
# coding=UTF-8 '''此文件主要是获取cfg.ini中对应的配置信息'''
import os
import ConfigParser cur_path = os.path.dirname(os.path.realpath(__file__))
configpath = os.path.join(cur_path,"cfg.ini")
conf = ConfigParser.ConfigParser()
conf.read(configpath) smtp_server = conf.get("email","smtp_server") sender = conf.get("email","sender") psw = conf.get("email","psw") receiver = conf.get("email","receiver") port = conf.get("email","port") '''测试时通过print查看获取的值是否正确,不用释放开'''
# print cur_path
# print configpath
# print smtp_server
# print sender
# print psw
# print receiver
# print port
3、接收和发送邮件的主体内容
#!/usr/bin/env python
# coding=UTF-8 import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from Common.logs import logging
from Config.email import readConfig report_path = os.getcwd()[:-5] + '/Result/Report' + "/"
class email_L: def get_Report_file(self,report_path):
'''
用途:获取最新的API测试报告
参数介绍:
report_path:报告存储的路径
'''
logging.info("获取最新的测试报告")
lists = os.listdir(report_path)
#print lists
lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn)))
logging.info(u"最新测试生成的报告:" + lists[-1])
report_file = os.path.join(report_path, lists[-1])
return report_file def send_mail(self,sender, psw, receiver, smtpserver, report_file, port,status):
'''
用途:发送最新的测试报告
参数介绍:
sender:发送者
psw:QQ的授权码
receive:接收者
smtpserver:邮件的格式
report_file:发送的邮件附件
port:邮箱的端口
'''
logging.info("邮件发送最新的API测试报告")
with open(report_file, "rb") as f:
mail_body = f.read() # 定义邮件内容
msg = MIMEMultipart()
body = MIMEText(mail_body, _subtype="html", _charset="utf-8")
msg['subject'] = u"【%s】iBer接口自动化测试报告"%status
msg['from'] = sender
msg['to'] = psw
msg.attach(body) # 添加附件
att = MIMEText(open(report_file, "rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
att["Content-Disposition"] = 'attachment;filename = "report.html"'
msg.attach(att)
try:
smtp = smtplib.SMTP_SSL(smtpserver, port)
except:
smtp = smtplib.SMTP()
smtp.connect(smtpserver, port) # 用户名和密码
smtp.login(sender, psw)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
logging.info("API测试报告已发送成功 !")
receiver = readConfig.receiver
logging.info("已发送的邮箱: %s" %receiver) def test_run(self,status):
'''如上2个方法的集合整理方法''' report_file = self.get_Report_file(report_path)
# 邮箱配置
sender = readConfig.sender
psw = readConfig.psw
smtp_server = readConfig.smtp_server
port = readConfig.port
receiver = readConfig.receiver
self.send_mail(sender, psw, receiver, smtp_server, report_file, port,status) # 发送报告
4、Run_Test.py 主要是针对测试结果,发送邮件。在你的接口测试执行结束后,添加此段代码即可
from Common.email_L import email_L #调用的写法根据你自己的文件路径来写
y = email_L()
y.test_run() #无论成功失败均发送邮件
升级版,结合unittest框架,根据测试结果判断邮件发送的格式和内容:
执行结果中有失败的项,接收的邮件标题:【FAIL】接口自动化测试报告
执行结果全部成功,接收的邮件标题:【PASS】接口自动化测试报告
注:
logging:是我自己封装的logs模块。若你没有,则直接注释,用print打印结果
suite:result = runner.run(suite) 是对所有测试用例的合集(不会者可查看下:https://blog.csdn.net/ljl6158999/article/details/80994979)
#!/usr/bin/env python
# coding=UTF-8 import os,time
import unittest
from Common.logs import logging
from Test.Case.Z_Case_collects import suite
import Common.HTMLTestRunner2
from Common.email_L import email_L class run(unittest.TestCase): def test_Runtest(self):
now = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
File_Path = os.getcwd()[:-5]+ '/Result/Report' + "/" # 获取到当前文件的目录,并检查是否有report文件夹,如果不存在则自动新建report文件
#print File_Path
if not os.path.exists(File_Path):
os.makedirs(File_Path)
#logging.info(File_Path)
Report_FileName = file(File_Path + now + r"_API测试报告.html", 'wb')
runner = Common.HTMLTestRunner2.HTMLTestRunner(stream=Report_FileName, title="接口测试报告",
description="用例执行情况:",verbosity=2) #verbosity=2:将会取到方法名下的注释内容 result = runner.run(suite) ## suite为Case_Gathers.py中的suite,用法:将case中的suite添加到报告中生成 Report_FileName.close() ################################如下:测试结果邮件发送给对应接收者################################### # print "运行成功的数目",result.success_count
# print "运行失败的数目",result.failure_count
# print "运行测试用例的总数",Common.HTMLTestRunner2.HTMLTestRunner.total time.sleep(2)
y = email_L()
#y.test_run() #无论成功失败均发送邮件 if result.success_count != Common.HTMLTestRunner2.HTMLTestRunner.total:
y.test_run(status = "FAIL") #接口用例有执行失败,则发送的邮件标题中会标出【Fail】
logging.error("用例中执行有失败,请查看邮件!!!!")
else:
y.test_run(status="PASS") #与上面反之,标注【Pass】
logging.error("用例执行全部成功,请查看邮件!!!!") if __name__ == "__main__":
unittest.main()
实现结果示例:

本文的来自也是参考上海-悠悠的博客贡献并自己通过添加某些实现和封装,再次根据自己项目的特性和框架编写所得。,可参阅:https://www.cnblogs.com/yoyoketang/p/7259993.html,
Python+request+ smtplib 测试结果html报告邮件发送(下)《六》的更多相关文章
- Python+request+ smtplib 测试结果html报告邮件发送(上)《五》
此方法通用适合所有邮箱的使用,只需注意几个点,如下: QQ邮箱.其他非QQ邮箱的写法,区别点如下: #--------------------------使用腾讯企业邮箱作为发件人的操作如下----- ...
- 【Linux】结合Python 简易实现监控公司网站,邮件发送异常
背景 由于一些原因,博主负责测试的网站的服务器切换到了香港,切换后出现了多次访问超时的情况 于是主动请缨写一个自动监测的脚本,本来准备完全使用shell来写,后来发现shell发送邮件只能在测试机之间 ...
- python初级实战-----关于邮件发送问题
python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用.smtplib模块主要负责发送邮件,email模块主要负责构造邮件. sm ...
- Python SMTP邮件发送
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件.HTML邮件以及带附件的邮件. Python对SMTP支持有smtplib和email两个模块: email负责构造邮件 ...
- spring各种邮件发送
参考地址一 参考地址二 参考地址三 参考地址四 Spring邮件抽象层的主要包为org.springframework.mail.它包括了发送电子邮件的主要接口MailSender,和值对象Simpl ...
- 使用python的email、smtplib、poplib模块收发邮件
使用python的email.smtplib.poplib模块收发邮件 一封电子邮件的旅程是: MUA:Mail User Agent——邮件用户代理.(即类似Outlook的电子邮件软件) MTA: ...
- python的email、smtplib、poplib模块收发邮件
一封电子邮件的旅程是: MUA:Mail User Agent--邮件用户代理.(即类似Outlook的电子邮件软件) MTA:Mail Transfer Agent--邮件传输代理,就是那些Emai ...
- python基础之psutil模块和发邮件(smtplib和yagmail)
除了内建的模块外,Python还有大量的第三方模块. 基本上,所有的第三方模块都会在PyPI - the Python Package Index上注册,只要找到对应的模块名字,即可用pip安装. 此 ...
- 初识python 之 smtplib 发送(dolphinscheduler任务监测)邮件
需求 监测dolphinscheduler调度系统,任务执行异常情况.如有异常,则发送邮件通知. 处理思路 因DS本身自带的邮件发送功能,不能正常发送邮件. 故而,通过查询DS源数据表,获取当前任务执 ...
随机推荐
- 浅谈UML的概念和模型
讲了UML的基本的九种图:http://blog.csdn.net/jiuqiyuliang/article/details/8552956 来具体讲讲这九种视图: 1.用例图(use case di ...
- java日志框架系列(7):logback框架Layout详解
1.Layout layout从字面意思来看就是排版.布局咯. 1.Layout简介 功能:负责把事件转换成字符串.Layout接口的格式化方法doLayout()负责将代表任何类型的事件的转换成一个 ...
- PHP生成有背景的二维码图片
Hart QR Code 快速生产带背景的二维码,他为你提供了以下功能 生产原始二维码,可配置url或则text,以及二维码大小 生产带背景带二维码,背景大小是你传入带背景大小,可配置原始二维码大小, ...
- c++学习---const 和 string
当在两个文件定义了同名的const变量时,相对于定义了两个独立的变量 想要在一个文件中定义一个const变量并在其他文件中使用他:不管时声明还是定义,都加上extern关键字 因为const对象一经初 ...
- springboot项目在IDEA根据不同的开发人员读取不同的配置文件
IDEA启动项目打开项目的配置文件,修改Program argument为--spring.profiles.active=developerName启动项目,即可 命令行方式启动项目 java -j ...
- 怎样理解this
JavaScript里的this, Python里的self, 其实都是一个东西, 它的存在跟构造函数 / 类这种是分不开的, 当然, 也可以在其他场合下使用, 他的意义很多, 但最共通的一个特点是: ...
- .net core下对于Excel的一些操作及使用
原文:.net core下对于Excel的一些操作及使用 版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.cs ...
- SQL Server 2017命令创建新账户(test-user),并分配数据库权限
-- 1. 创建登录账号USE [master];GOCREATE LOGIN [test-user] WITH PASSWORD = 'xysu7SZ193SNX6E{{HxubPE3}vr',DE ...
- Linq to sql之left join运用示例
示例一: var l= from a in cardsBll.GetCards() join b in usersBll.GetAllUsers() on a.CardSn equals b.Card ...
- [书籍翻译] 《JavaScript并发编程》第七章 抽取并发逻辑
本文是我翻译<JavaScript Concurrency>书籍的第七章 抽取并发逻辑,该书主要以Promises.Generator.Web workers等技术来讲解JavaScrip ...