【10】Selenium+Python UI自动化测试 邮件发送测试报告(某积载系统实例-04)

测试报告需要发送给相关人员,但每次都要在report目录下去复制太麻烦,可以使用邮件模块自动将生成的报告发送给相关人员

1、 新增utils文件夹,用于存放工具文件

在utils下新增sendmail.py文件

代码
sendmail.py

python 复制代码
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from Test.pythonProject.test_selenium_pjz.run import report_dir


def sendmail():
    host = 'smtp.qq.com'
    sender = '****@qq.com'  # 发送方邮件地址
    passwd = '****'  # 发送方密码  需要在邮箱设置中开启SMTP服务 并获取授权码,此处是填写获取的授权码
    receiver = '****@qq.com'  # 接收报告方邮件地址

    msg = MIMEMultipart()
    msg['from'] = sender
    msg['to'] = receiver
    msg['subject'] = '主题'
    msg.attach(MIMEText('邮件正文'))
    import os
    print(os.path.abspath(__file__))
    att1 = MIMEText(open(report_dir, 'rb').read().decode('utf-8'), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
    att1["Content-Disposition"] = 'attachment; filename="report.html"'
    msg.attach(att1)

    try:
        smtpobj = smtplib.SMTP_SSL(host, port=465)#我使用的是QQ邮箱 所以用这个方法,不同的邮箱,这个方法可能不同,如果使用错误的方法,可能会导致连接关闭问题,无法发送邮件
        smtpobj.login(sender, passwd)
        smtpobj.sendmail(sender, receiver, msg.as_string())
        smtpobj.quit()
        print('send success')
    except smtplib.SMTPException as e:
        print(e)
        print('send err')

2、 修改run.py 调用sendmail函数
代码
run.py

python 复制代码
import unittest
import time
from HTMLTestRunner import HTMLTestRunner
from Test.pythonProject.test_selenium_pjz.utils import sendmail

testdir = "./cases"
discover = unittest.defaultTestLoader.discover(start_dir=testdir, pattern='test*.py')
cur_time = time.strftime('%Y-%m-%d %H_%M_%S', time.localtime(time.time()))
report_name = "HTMLReport"+cur_time+".html"
report_dir="./report/{}".format(report_name)

if __name__ == '__main__':

    with open(report_dir, 'w', encoding='utf-8') as f:
        runner = HTMLTestRunner.HTMLTestRunner(stream=f,
                                title='pjz测试报告名称',
                                description='pjz 测试描述信息',
                                verbosity=2)
        runner.run(discover)

    sendmail.sendmail()
相关推荐
程序员佳佳1 小时前
2025年大模型终极横评:GPT-5.2、Banana Pro与DeepSeek V3.2实战硬核比拼(附统一接入方案)
服务器·数据库·人工智能·python·gpt·api
刘某的Cloud2 小时前
列表、元组、字典、集合-组合数据类型
linux·开发语言·python
ys~~2 小时前
git学习
git·vscode·python·深度学习·学习·nlp·github
Mqh1807622 小时前
day46 Grad-CAM
python
郝学胜-神的一滴2 小时前
Python魔法函数一览:解锁面向对象编程的奥秘
开发语言·python·程序人生
白露与泡影3 小时前
使用systemd,把服务装进 Linux 心脏里~
linux·运维·python
yaoh.wang3 小时前
力扣(LeetCode) 100: 相同的树 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
Sunsets_Red3 小时前
2025 FZYZ夏令营游记
java·c语言·c++·python·算法·c#
guslegend3 小时前
第2章:LangChain大模型工具开发(Agent工具能力)
python
草帽lufei4 小时前
Ubuntu中为AI Agent相关开发配置Python环境
python·agent·ai编程