#用于发送测试报告(带附件)或其它内容# -*- coding:utf-8 -*-
import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipartclass SendEmail(object):def __init__(self, receivers):mail_host = "127.0.0.1" # SMTP服务器mail_user = "username" # 用户名mail_pass = "password" # 密码sender = "123456@qq.com" # 发件人邮箱file_path = os.path.dirname(os.path.dirname(__file__)) + '\\report\\test_result.html' # 拼接测试报告的路径title = '自动化测试结果' # 邮件主题mail_body = "查看测试报告请下载附件!!!"message = MIMEMultipart()message['From'] = "{}".format(sender) # 从哪发出邮件 message['To'] = ",".join(receivers) # receivers:接收人邮箱地址message['Subject'] = title # 标题msgtext = MIMEText(mail_body, _subtype='plain', _charset='utf-8') # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码message.attach(msgtext) # 添加主邮件主体内容# 添加一个HTML文本附件ff = open(file_path, 'rb')att = MIMEText(ff.read(), 'base64', 'utf-8')# 附件设置内容类型,设置为二进制流att["Content-Type"] = 'application/octet-stream'# 设置附件头,添加文件名,filename 可以随意写att["Content-Disposition"] = 'attachment; filename="test_result.html"'# 解决中文附件名乱码问题# att.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', basename))message.attach(att)ff.close()try:smtpObj = smtplib.SMTP(mail_host, 25) # 25 是指定 SMTP 服务使用的端口号,默认 25"""SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。"""smtpObj.login(mail_user, mail_pass) # 登陆邮箱smtpObj.sendmail(sender, receivers, message.as_string()) # 发送邮件(发信人,收件人,邮件内容),这里需要注意邮件内容的格式,这个格式就是 smtp 协议中定义的格式print("邮件已成功发送")smtpObj.quit()except smtplib.SMTPException as e:print(e)if __name__ == "__main__":SendEmail(["123456@qq.com", "123467@qq.com"])