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

配置与实现代码分隔编写,详见如下:

目录结构如下:

1、cfg.ini的配置信息写法如下:

[email]
;--------------------------使用腾讯企业邮箱作为发件人的操作如下---------------------
smtp_server = smtp.qq.com
Port = 465
Sender = 请写你自己的QQ邮箱
psw = 请写你自己的QQ授权码
Receiver = [email protected]   (注:请写你的邮件收件人邮箱)

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/syw20170419/p/10949285.html

时间: 2024-08-07 08:02:19

Python+request+ smtplib 测试结果html报告邮件发送(下)《六》的相关文章

Python 提取数据库(Postgresql)并邮件发送

刚入门python,发现确实是一个不错的语言. 业务部门要求将将某一个数据库中的表,定期发送到相关部门人员邮箱. 其实整个业务需求很简单,实现起来也不难. 但是由于刚入门python,所以还是借鉴了不上网上的内容,也得到了许多群友的提醒. 业务部门使用的是Postgresql数据库,所以使用 了psyconpg2的模块. 整个脚本分为三部分: 1.数据库的连接及数据写入excel表中(整个对新手来说,应该是难点) 2.邮件的发送 3.生成excel文件的删除 # coding: utf-8 im

spring各种邮件发送

参考地址一 参考地址二 Spring邮件抽象层的主要包为org.springframework.mail.它包括了发送电子邮件的主要接口MailSender,和值对象SimpleMailMessage,它封装了简单邮件的属性如from, to,cc,subject,text. 包里还包含一棵以MailException为根的checked Exception继承树,它们提供了对底层邮件系统异常的高级别抽象. 要获得关于邮件异常层次的更丰富的信息,请参考Javadocs. 为了使用JavaMail

Mailx解决Linux报警邮件发送问题

在做服务器监控的时候,有的使用专业的zabbix监控来解决,但是有的个别机器可能只是临时脚本监控一下,这个时候可能也需要一个介质来发送警报,如果公司内部有邮件服务器postfix还好没有的话,再搞一个域名什么的也太麻烦.Mailx就可以解决这样一个问题,通过mailx配置好发送服务器的相关信息就可以了 安装: [[email protected] ~]# rpm -q mailx mailx-12.4-7.el6.x86_64 我印象里这个好像不用装,因为系统会预装的,先rpm -q一下,如果没

Windows下利用Python动态检测外网IP并发邮件给邮箱

我们知道,运营商给分配的都是动态IP,IP地址过一段时间会自己变化,这就给需要静态地址的应用带来不便,例如搭建服务器或者远程控制电脑,这种情况必须知道自己电脑的IP,利用Python可以方便的自动检测并向邮箱发送邮箱. 但是,个人网络一般都是通过路由器来上网,直接检测电脑的IP并不可行,需要得到外网的IP.内网电脑可以通过端口映射来映射到外网.检测的原理如下: 1.通过自己的电脑信息不太好获取外网IP,幸好有一些雷锋网站可以帮助我们来检测,例如 http://city.ip138.com/ip2

python 邮件发送

#!/usr/bin/env python # -*- coding:UTF-8 -*- #需要在邮箱处设置开启SMTP服务(第三方客户端发送) import smtplibfrom email.mime.text import MIMETextfrom email.utils import formataddrdef mail(): ret = True try: msg = MIMEText('测试邮件','plain','utf-8') msg['From'] = formataddr([

python实现邮件发送完整代码(带附件发送方式)

实例一:利用SMTP与EMAIL实现邮件发送,带附件(完整代码) __author__ = 'Administrator'#coding=gb2312 from email.Header import Headerfrom email.MIMEText import MIMETextfrom email.MIMEMultipart import MIMEMultipartimport smtplib, datetime def SendMailAttach(): msg = MIMEMultip

python学习笔记2:基础(邮件发送)

参考文档:http://www.runoob.com/python/python-email.html SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式. python的smtplib提供了一种很方便的途径发送电子邮件.它对smtp协议进行了简单的封装. Python创建 SMTP 对象语法如下: import smtplib smtpObj = smtplib.SMTP( [host

邮件发送Python脚本

#!/usr/bin/env python2 #-*- coding: utf-8 -*- #导入smtplib,sys import smtplib,sys from email.mime.text import MIMEText def send_mail(sub,content): #要发给谁,这里发给1个人 mailto_list=["[email protected]", "[email protected]"] #设置服务器用户名.口令以及邮箱后缀 ma

python模块:smtplib模块

1.使用本地的sendmail协议进行邮件发送 格式(1):smtpObj=smtplib.SMTP([host [,port [,local_hostname]]]) host:SMTP服务器主机的IP地址或者是域名 port:服务的端口号(默认是25) local_hostname:服务器的地址(默认是localhost) 格式(2):SMTP.sendmail(from_addr),to_addrs,msg[,mail_options,rcpt_options] from_addr:邮件发