目录结构如下:

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报告邮件发送(下)《六》的更多相关文章

  1. Python+request+ smtplib 测试结果html报告邮件发送(上)《五》

    此方法通用适合所有邮箱的使用,只需注意几个点,如下: QQ邮箱.其他非QQ邮箱的写法,区别点如下: #--------------------------使用腾讯企业邮箱作为发件人的操作如下----- ...

  2. 【Linux】结合Python 简易实现监控公司网站,邮件发送异常

    背景 由于一些原因,博主负责测试的网站的服务器切换到了香港,切换后出现了多次访问超时的情况 于是主动请缨写一个自动监测的脚本,本来准备完全使用shell来写,后来发现shell发送邮件只能在测试机之间 ...

  3. python初级实战-----关于邮件发送问题

    python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用.smtplib模块主要负责发送邮件,email模块主要负责构造邮件. sm ...

  4. Python SMTP邮件发送

    SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件.HTML邮件以及带附件的邮件. Python对SMTP支持有smtplib和email两个模块: email负责构造邮件 ...

  5. spring各种邮件发送

    参考地址一 参考地址二 参考地址三 参考地址四 Spring邮件抽象层的主要包为org.springframework.mail.它包括了发送电子邮件的主要接口MailSender,和值对象Simpl ...

  6. 使用python的email、smtplib、poplib模块收发邮件

    使用python的email.smtplib.poplib模块收发邮件 一封电子邮件的旅程是: MUA:Mail User Agent——邮件用户代理.(即类似Outlook的电子邮件软件) MTA: ...

  7. python的email、smtplib、poplib模块收发邮件

    一封电子邮件的旅程是: MUA:Mail User Agent--邮件用户代理.(即类似Outlook的电子邮件软件) MTA:Mail Transfer Agent--邮件传输代理,就是那些Emai ...

  8. python基础之psutil模块和发邮件(smtplib和yagmail)

    除了内建的模块外,Python还有大量的第三方模块. 基本上,所有的第三方模块都会在PyPI - the Python Package Index上注册,只要找到对应的模块名字,即可用pip安装. 此 ...

  9. 初识python 之 smtplib 发送(dolphinscheduler任务监测)邮件

    需求 监测dolphinscheduler调度系统,任务执行异常情况.如有异常,则发送邮件通知. 处理思路 因DS本身自带的邮件发送功能,不能正常发送邮件. 故而,通过查询DS源数据表,获取当前任务执 ...

随机推荐

  1. Linux IO的五种模型 ongoing

    服务器端编程经常需要构造高性能的IO模型,常见的IO模型: 阻塞I/O模型  (Blocking IO) ------------(同步)(阻塞) 非阻塞I/O模型 (Non-Blocking IO) ...

  2. Eureka如何剔除已经宕机的节点

    同一个服务部署了多个实例,在通过网关调用时会随机调用其中一个.但是,当某个服务挂掉之后,依然在注册中心中,依然会随机被调用到,调用时便会超时报错.(主要是开发测试或者演示时需要立即将失效的从注册中心剔 ...

  3. 1.Cloudera Manager安装

    安装环境采用2台虚拟机进行,一台master, 一台slave1 先安装好centos 6.5 两台,并设置静态ip 怎么安装可以参考地址:https://jingyan.baidu.com/arti ...

  4. ruby tk实现简易计算器

    #encding:GBK require 'tk' module Const WIDTH_OF_PANEL = 370 HEIGHT_OF_PANEL = 520 SIZE_OF_BUTTON_H = ...

  5. sql server 2012 链接服务器不能链接sql server 2000的解决方案 ,

    本数据源来自 https://www.kafan.cn/edu/922556.html  目的为了备忘 把原来的sql server 2005直接装成了2012,然后在建立链接服务器链接一台sql s ...

  6. python学习-21 集合 2

    集合的其他方法 1.交差补集 math = {'xm','xh','xg','xx'} english ={'xm','xh','dm','john'} print(math.symmetric_di ...

  7. 将物理机系统转为虚拟机系统 p2v

    ref : https://blog.csdn.net/gsls200808/article/details/77932713 背景: 在公司有台机子主要负责某产品的升级与维护,出于各种原因,该产品需 ...

  8. 阿里云Centos7 搭建laravel

    最近在考虑学习laravel框架,唔 现在服务器搭建一下. laravel是依赖composer的,首先在linux服务器下先安装composer.运行composer需要 php 5.3以上版本, ...

  9. ELK日志分析系统的搭建

    一.ELK简介 ELK是Elasticsearch.Logstash.Kibana的简称,这三者是核心组件. Elasticsearch是数据存储.搜索.分析引擎,功能非常强大:Logstash是日志 ...

  10. 十二、react-reudx之@connect 摆脱redux的繁琐操作

    如果对redux的概念和用法掌握的已经不错了 那么现在react-redux会让你的操作更加的得心印手 忘记subscribe,记住reducer,action和dispatch即可     Reac ...