Python执行完测试用例,自动发送邮件(一)

本文介绍了如何在Python中创建sendmail.py和test.py文件,用于在执行完测试用例后自动发送邮件。在sendmail.py中设置邮件发送者的地址和授权码,在test.py中配置邮件内容、标题及接收者信息。
摘要由CSDN通过智能技术生成

1、新建sendmail.py文件

需要修改 邮件发送者地址、邮箱授权码

import yagmail
import time


class Mail:
    """
    邮件相关类
    """

    def log(self, content):
        now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        print(f'{now_time}: {content}')

    def sendmail(self, msg, title, receivers):
        """
        发送邮件

        Arguments:
            msg {str} -- 邮件正文
            title {str} -- 邮件标题
            receivers {list} -- 邮件接收者,数组
        """

        yag = yagmail.SMTP(
            host='smtp.qq.com', user='邮件发送者地址',
            password='邮箱授权码', smtp_ssl=True
        )

        try:
            yag.send(receivers, title, msg)
            self.log("邮件发送成功")

        except BaseException as e:
            print(e)
            self.log("Error: 无法发送邮件")
<
可以根据以下代码实现Python自动化测试用例只有执行失败才发送邮件: ``` import smtplib, unittest class Test(unittest.TestCase): def test_pass(self): self.assertEqual(2 + 2, 4) def test_fail(self): self.assertEqual(1 + 1, 3) def send_email(): # 定义邮件内容 SUBJECT = 'Python自动化测试用例失败邮件' BODY = 'Python自动化测试用例有失败,请及时查看!' # 发送邮件 smtp_server = 'smtp.qq.com' smtp_port = '587' smtp_sender = 'your_email@qq.com' smtp_password = 'your_email_password' smtp_receiver = 'receiver_email@qq.com' smtp_obj = smtplib.SMTP(smtp_server, smtp_port) smtp_obj.starttls() smtp_obj.login(smtp_sender, smtp_password) smtp_obj.sendmail(smtp_sender, smtp_receiver, 'Subject: {}\n\n{}'.format(SUBJECT, BODY)) smtp_obj.quit() if __name__ == '__main__': suite = unittest.TestSuite() suite.addTest(Test('test_pass')) suite.addTest(Test('test_fail')) runner = unittest.TextTestRunner() result = runner.run(suite) for failure in result.failures: send_email() break ``` 在以上代码中,我们首先导入了`smtplib`和`unittest`模块。然后定义了一个测试类`Test`,其中包含两个测试用例,一个是成功的用例,一个是失败的用例。接着定义了一个发送邮件的函数`send_email()`,用于在测试用例失败时发送邮件。最后,在`if __name__ == '__main__'`中,我们将两个测试用例加入测试套件中,并通过`TextTestRunner`来运行测试用例,当有失败的用例时,通过`for`循环调用`send_email()`函数发送邮件通知。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大城市的小人物

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值