py3发送使用QQ邮箱发送html附件
from email.mime.text import MIMEText
import smtplib
import smtplib
from email.mime.multipart import MIMEMultipart
from email.utils import formataddr
import os
import time
reportPath = 'C:\Logs\logs'
class SendEmail:
def get_report(self):#该函数作用是为了在测试报告的路径下找到最新的测试报告
dirs = os.listdir(reportPath)#返回文件下的文件名、文件夹的列表
dirs.sort()
newreportname = dirs[-1]
print('The new report name:{0}'.format(newreportname))
return newreportname
def take_message(self):#该函数目的是为了准备发送邮件的消息内容
newreport = self.get_report()
self.msg = MIMEMultipart()#创建一个附件实例
self.msg['Subject'] = 'xxx接口测试用例报告'#邮件标题
self.msg['date'] = time.strftime('%a,%d %b %Y %H:%M:%S %z')
with open(os.path.join(reportPath,newreport),'rb') as f:
mailbody = f.read()
#html = MIMEText(mailbody,_subtype='html',_charset='utf-8')
#self.msg.attach(html) #html附加在msg里 打开html文件,并显示在邮件正文当中
from email.utils import formataddr
import os
import time
reportPath = 'C:\Logs\logs'
class SendEmail:
def get_report(self):#该函数作用是为了在测试报告的路径下找到最新的测试报告
dirs = os.listdir(reportPath)#返回文件下的文件名、文件夹的列表
dirs.sort()
newreportname = dirs[-1]
print('The new report name:{0}'.format(newreportname))
return newreportname
def take_message(self):#该函数目的是为了准备发送邮件的消息内容
newreport = self.get_report()
self.msg = MIMEMultipart()#创建一个附件实例
self.msg['Subject'] = 'xxx接口测试用例报告'#邮件标题
self.msg['date'] = time.strftime('%a,%d %b %Y %H:%M:%S %z')
with open(os.path.join(reportPath,newreport),'rb') as f:
mailbody = f.read()
#html = MIMEText(mailbody,_subtype='html',_charset='utf-8')
#self.msg.attach(html) #html附加在msg里 打开html文件,并显示在邮件正文当中
#html附件 下面是将测试报告放到附件中发送
email_text = MIMEText('测试报告')
att1 = MIMEText(mailbody,'base64','utf-8')
att1['Content-Type'] = 'application/octet-stream'
att1['Content-Disposition'] = 'attachment; filename=%s'%newreport #filename为文件名,发送为什么就写什么
self.msg.attach(att1) #将html文件作为附件添加到邮件当中
self.msg.attach(email_text) #将email_text添加到正文内容
def send(self):
my_email = '[email protected]' #QQ账号
my_pass = 'xxxxx' #QQ授权码
send_email = '[email protected]'# #如果接收者为163邮箱,可能会存在正文内容为txt文件
self.take_message()
self.msg['from'] = formataddr(['xx测试',my_email]) #将邮箱名称以化名进行显示 方便领导知道邮件来源
self.msg['to'] = formataddr(['J',send_email])
smtp = smtplib.SMTP_SSL('smtp.qq.com ',465) #QQ邮箱服务以及端口
smtp.ehlo()
smtp.login(my_email,my_pass) # 进行登录QQ邮箱
smtp.sendmail(my_email,[send_email],self.msg.as_string())
#括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件操作
#由于sendemail要传String类型,所以要用.as_string()把内容组合成字符串
smtp.quit() #关闭连接
print('sendemail success')
if __name__ == '__main__':
sendMail = SendEmail()
sendMail.send()
#由于sendemail要传String类型,所以要用.as_string()把内容组合成字符串
smtp.quit() #关闭连接
print('sendemail success')
if __name__ == '__main__':
sendMail = SendEmail()
sendMail.send()
如有更优化内容,请多多指点