【python+unittest 接口自动化测试实战 (三)】-- 获取最新的测试报告并发送邮件

一、目录结构 

 

读取邮箱配置参考:https://blog.csdn.net/kk_gods/article/details/109054888

二、实现

1、导入相关库


# coding=utf-8
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib,os

2、获取要发送的测试报告

测试报告文件夹下可能存在多个测试报告,所以在这里只获取最新的测试报告

def get_report_file(report_path):
    """
    获取最新的测试报告
    :param report_path:
    :return:
    """
    lists = os.listdir(report_path)
    lists.sort(key=lambda fn: os.path.getmtime(os.path.join(report_path, fn)))
    print(u'最新测试生成的报告: '+lists[-1])
    # 找到最新生成的报告文件
    report_file = os.path.join(report_path, lists[-1])
    return report_file

 3、发送邮件

def send_mail(sender, psw, receiver, cc_receiver, smtpserver, report_file, port):
    """发送最新的测试报告内容"""
    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"接口自动化测试报告"
    msg["from"] = sender
    msg["to"] = ",".join(receiver)
    msg["Cc"] = ",".join(cc_receiver)
    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)
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver, port)
    # 用户名密码
    smtp.login(sender, psw)
    smtp.sendmail(sender, receiver+cc_receiver, msg.as_string())
    smtp.quit()
    print('Test report email has send to {} !'.format(receiver))

 4、获取发件邮箱、收件邮箱、抄送邮箱地址(参考https://blog.csdn.net/kk_gods/article/details/109054888)并发送

def main():
    # 获取最新的测试报告文件
    report_path = os.path.join(cur_path, "report")  # 测试报告文件夹
    report_file = get_report_file(report_path)  # 获取最新的测试报告
    print('report_file: ', report_file)
    # 邮箱配置
    sender = readconfig.sender
    psw = readconfig.psw
    smtp_server = readconfig.smtp_server
    port = readconfig.port
    receivers = readconfig.receiver.split(',')
    cc_receiver = readconfig.cc_receiver.split(',')
    send_mail(sender, psw, receivers, cc_receiver, smtp_server, report_file, port)  # 发送报告

 

if __name__ == "__main__":
    main()

 三、测试报告邮件效果

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值