解决问题:unittest发送带附件的邮件,下载后打开,报告内容空白!!
如下:
原出错代码如下:
1. run.py文件:
import unittest,HTMLTestRunner,time
from utils.log_cn import mkdir
from utils.TestAutoEmail import SendMailAttach
from time import sleep
suite=unittest.defaultTestLoader.discover('./case',pattern='test_Pro*.py')
if __name__ == '__main__':
# 获取当前时间,这样便于下面的使用。
now = time.strftime('%Y_%m_%d %H_%M_%S')
mkdir('./report/' + now[:-9]) #调用log_cn的mkdir,在report下创建文件夹,[:-9]切片-9从后向前的9个位置切开
filename='./report/' +now[:-9]+'/html/'+ now + '.html'
fp = open(filename,'wb')
runner = HTMLTestRunner.HTMLTestRunner(open(filename,'wb'),
title='测试报告',
description='测试内容')
runner.run(suite)
SendMailAttach(filename)
调试后发现在发邮件时,filename内容为空!
我犯了个大概只有我自己会犯的错误5555555
解决:
SendMailAttach(filename) 跳出当前if函数,改为:
import unittest,HTMLTestRunner,time
from utils.log_cn import mkdir
from utils.TestAutoEmail import SendMailAttach
from time import sleep
suite=unittest.defaultTestLoader.discover('./case',pattern='test_Pro*.py')
if __name__ == '__main__':
# 获取当前时间,这样便于下面的使用。
now = time.strftime('%Y_%m_%d %H_%M_%S')
mkdir('./report/' + now[:-9]) #调用log_cn的mkdir,在report下创建文件夹,[:-9]切片-9从后向前的9个位置切开
filename='./report/' +now[:-9]+'/html/'+ now + '.html'
fp = open(filename,'wb')
runner = HTMLTestRunner.HTMLTestRunner(open(filename,'wb'),
title='测试报告',
description='测试内容')
runner.run(suite)
SendMailAttach(filename)
完美解决!!!附件终于有内容了!!
附上:定义的发送邮件文件: TestAutoEmail.py
import smtplib,datetime,time
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
from time import sleep
def SendMailAttach(filename): #发送附件邮件
smtpserver = 'smtp.126.com'
user = "aidong**@126.com" # 发送邮件的邮箱
sender_pwd = '**' #授权码!!!
sender = 'aidongch**e@126.com' #发送邮箱
receiver = '962093265@qq.com'
msg = MIMEMultipart()
now = time.strftime('%Y_%m_%d %H_%M_%S')
# open(filename).close()
sleep(2)
att = MIMEText(open(filename, "r", encoding='UTF-8').read(),'html') # 邮件类型:html格式
print(filename)
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attchment; filename="'+filename[25:]+'"' #filename的左侧第25位向右取值到末尾
# att["Content-Disposition"] = 'attchment; filename="2021_11_16.html"' # 附件名称为2021_11_16.html
msg.attach(att)
msg["from"] = sender # 发件人
msg["to"] = receiver # 收件人
# msg["to"] = ";".join(receiver) # 多个收件人 list 转 str
msg["subject"] = Header('带附件测试结果') # 发送的邮件的主题
body = 'Python test'
msg.attach(MIMEText(body,'plain'))
smtp = smtplib.SMTP()
smtp.connect(smtpserver) # 连服务器
smtp.login(user, sender_pwd)
smtp.sendmail(msg["from"], msg["to"], msg.as_string())
smtp.quit()
其中,对filename多次调试,均失败