第一步:发送邮件模块封装,以下以QQ邮箱为例:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
def send_email_fujian(fujian_path,file_name):
mail_host = "smtp.qq.com" # 设置服务器
mail_user = "xxxxxx@qq.com" # 用户名
mail_pass = "qefidvxpbltxdfha" # 口令
sender = 'xxxxxx@qq.com'
receivers = ['xxxxxx@qq.com'] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
# 创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("发送邮件", 'utf-8')
message['To'] = Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')
# 邮件正文内容
message.attach(MIMEText('这是Python 邮件发送测试……', 'plain', 'utf-8'))
# 构造附件
att1 = MIMEText(open(fujian_path, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename=report.html'
message.attach(att1)
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号
smtpObj.login(mail_user, mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
第二步:应用发送邮件模块(运行测试用例,将生成的测试报告,发到邮箱):
import unittest, HTMLTestRunner, time,os
from send_email import email_utls
if __name__ == '__main__':
current_path = os.path.dirname(__file__)
case_path = current_path
all_case = unittest.defaultTestLoader.discover(start_dir=case_path,
pattern='test_*.py',
top_level_dir=None)
main_suit = unittest.TestSuite()
main_suit.addTest(all_case)
report_path = current_path '/../report/TestReport_' time.strftime('%Y-%m-%d_%H_%M_%S ', time.localtime(time.time())) '.html'
fp = open(report_path, 'w', encoding='utf-8')
runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
title="测试报告",
description="用例执行情况")
runner.run(main_suit)
#发送邮件
email_utls.send_email_fujian(report_path,'TestReport_' time.strftime('%Y-%m-%d_%H_%M_%S ', time.localtime(time.time())) '.html')
收到的邮件和运行生成的测试报告:
,