python-发送html文件内容的邮件,并将html作为附件发送

import unittest
import os
from cases.api_case import Apicases #从case目录下的api_case文件中导入Apicases这个类
from HTMLTestRunner import HTMLTestRunner
import time
import datetime
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

#获取当前时间
now = datetime.datetime.now()
#转换为指定格式
OtherStyleTime = now.strftime('%Y-%m%d %H:%M:%S')

#创建测试套件
suite = unittest.TestSuite()
#添加测试用例
cases = [Apicases('test_1_login'),Apicases('test_2_token'),Apicases('test_3_employeeId'),Apicases('test_4_team')]

#继承测试报告
report_name = '接口自动化测试报告'
report_title = '接口测试报告' + OtherStyleTime
report_des = '接口测试报告描述' + '测试时间是' + OtherStyleTime
report_path = './report'
report_file = report_path + '.html' #测试报告名字(要加时间戳只能在'report.html'之前加,如:report_path + now + 'report.html')

#判断文件夹是否存在
if not os.path.exists(report_path):
os.mkdir(report_path)
else:
pass

with open(report_file,'wb') as report:
suite.addTests(cases)
runner = HTMLTestRunner(stream=report,title=report_title,description=report_des)
runner.run(suite)
print(11111111111111)

#第三方SMTP服务
mail_host = 'smtp.qq.com' #设置qq服务器
mail_user = '602***19@qq.com' #用户名
mail_pass = 'zsgkpfmydebkbfbj' #,密码(授权码)

sender = '602***619@qq.com' #发送者邮箱
receivers = ['w**an@nlelpct.com','60***19@qq.com'] #接受者邮箱

#读取html文件的内容
f = open("./report.html",'rb')
mail_body = f.read()
f.close()

#读取的HTML 形式的文件内容做为邮件的正文主题
html = MIMEText(mail_body,'html','utf-8') #邮件正文内容,plain:默认的写文本形式邮件的格式,如发送的是HTML,则plain改成HTML

# HTML附件 将测试报告放在附件中发送
att1 = MIMEText(mail_body,'base64','gb2312')
att1['Content-Type'] = 'application/octet-stream'
att1['Content-Disposition'] = 'attachment; filename = "lwy_aototest_report.html"' #filename是指下载的附件的命名

msg = MIMEMultipart()
msg.attach(html) #将html附加在msg里
msg.attach(att1) #新增一个附件
msg['Subject'] = 'lwy_自动化测试报告' #定义邮件主题
msg['From'] = Header('lwy_自动化测试报告','utf-8') #发送者
msg['To'] = Header('信息中心','utf-8') #接收者

try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host,25) #25是SMTP的端口号
smtpObj.login(mail_user, mail_pass) #登录邮箱
#SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
smtpObj.sendmail(sender,receivers,msg.as_string()) # ***.as_string()--***指的是邮件的各个主题、发送者
print('邮件发送成功')
except smtplib.SMTPException:
print('error:无法发送邮件')

运行结果

 


 

 

 


 

 
posted @ 2022-04-14 10:54  lllwy  阅读(1113)  评论(0编辑  收藏  举报