python中smtplib和MIMEText发送HTML邮件
# 邮件发送
import smtplib
import os
# 封装邮件内容
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
class MailSend():
def sendHtml(self):
# 设置发送邮箱服务器
smtpserver = "smtp.qq.com"
# 设置邮箱的用户名及密码,用于邮箱登录
username = '78@qq.com'
# 邮箱的授权码
password = '12'
# 设置发送邮箱
sender = username
# 设置接收邮箱
receiver = '5@163.com'
# 设置邮箱主题
subject = '自动化测试结果'
# 编写HTML类型的邮箱正文,及发送邮件的参数
# content = '<html><h1>自动化测试结果文件,请查收</h1></html>'
path = os.path.dirname(__file__)+r'/test_reports/'
# 通过读取html文件中的内容,然后发送
content = open(path+'2022-02-12-16-40-46.html','rb').read()
# MIMEText(msg,type,chartset)
# msg:文本内容,可自定义
# type:文本类型,默认为plain(纯文本)
# chartset:文本编码,中文为“utf-8”
msg = MIMEText(content,'html','utf-8')
# msg['Subject'] = subject
msg['Subject'] = Header(subject,'utf-8')
msg['From'] = sender
msg['To'] = receiver
# 创建一个邮件发送服务的对象
# smtp = smtplib.SMTP()
# QQ邮箱改为ssl方式发送了
smtp = smtplib.SMTP_SSL(smtpserver)
# 连接发件服务器
smtp.connect(smtpserver)
try:
# 登录发件邮箱
smtp.login(username,password)
# 发送邮件
smtp.sendmail(sender,receiver,msg.as_string())
except Exception as e:
print("邮件发送失败,出现异常:"+str(e.args)+'\n')
finally:
smtp.quit()
def sendFujian(self,filename):
# 设置发送邮箱服务器
smtpserver = "smtp.163.com"
# 设置邮箱的用户名及密码,用于邮箱登录
username = 'XXX@163.com'
# 邮箱的授权码
password = ''
# 设置发送邮箱
sender = username
# 设置接收邮箱
receiver = 'XXX@qq.com'
# 设置邮箱主题
subject = 'XXX自动化测试结果'
# 编写HTML类型的邮箱正文,及发送邮件的参数
# content = '<html><h1>自动化测试结果文件,请查收</h1></html>'
# 通过读取html文件中的内容,然后发送
path = os.path.dirname(__file__)+r'/test_reports/'+ filename + '.html'
content = open(path, 'rb').read()
msg = MIMEText(content, 'base64', 'utf-8')
msg['Content-Type'] = 'application/octer-stream'
# 设置在附件当中的名字
msg['Content-Disposition'] = "attachment;filename='%s.html'"%filename
# 邮件信息,内容为空 #相当于信封##related表示使用内嵌资源的形式,将邮件发送给对方
msgRoot = MIMEMultipart('related')
msgRoot['Subject'] = subject
msgRoot['From'] = sender
msgRoot['To'] = receiver
# 添加文件到邮件-附件中去
msgRoot.attach(msg)
# 创建一个邮件发送服务的对象
# smtp = smtplib.SMTP()
# QQ邮箱改为ssl方式发送了
smtp = smtplib.SMTP_SSL(smtpserver)
# 连接发件服务器
smtp.connect(smtpserver)
try:
# 登录发件邮箱
smtp.login(username, password)
# 发送邮件
smtp.sendmail(sender, receiver, msgRoot.as_string())
except Exception as e:
print("邮件发送失败,出现异常:"+str(e.args)+'\n')
finally:
smtp.quit()
if __name__ == '__main__':
ssend = MailSend()
ssend.sendHtml()
# ssend.sendFujian(r'2022-02-12-16-40-46.html')