python-email


import os
import smtplib

from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.header import Header

from API_AUTO_01.tools.my_log import MyLog
from API_AUTO_01.tools.project_path import *
from API_AUTO_01.tools.read_config import ReadConfig

my_logger = MyLog(test_log_path)


class SendEmail():
@staticmethod
def send_email(subject, mail_msg, mail_msg_type='plain', mail_attach=None):
email_config = eval(ReadConfig().read_config(test_config_path, "EMAIL", "email_config"))
sender = email_config['sender'] # 发件箱
sender_pwd = email_config['sender_pwd'] #发件箱密码
receivers = email_config['receivers'] # 收件箱列表
msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header('自动化测试服务器', 'utf-8') # 发件人别名
msgRoot['to'] = Header('干系人', 'utf-8') # 收件人别名
msgRoot['Subject'] = Header(subject, 'utf-8')

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)

msgRoot.attach(MIMEText(mail_msg, mail_msg_type, 'utf-8')) # 设置主体内容格式 plain 、html

mail_attachs = []
if type(mail_attach) == str:
mail_attachs.append(mail_attach)
else:
mail_attachs = mail_attach
attach_path = []
for item_path in mail_attachs:
print(item_path)
if os.path.isdir(item_path):
for i in os.listdir(item_path):
attach_path.append(os.path.join(item_path, i))
else:
attach_path.append(item_path)
print(attach_path)

for item in attach_path:
att1 = MIMEText(open(item, 'rb').read(), 'base64', 'utf-8') # 附件文件
att1["Content-Type"] = 'application/octet-stream' # 附件格式
att1["Content-Disposition"] = 'attachment; filename="{0}"'.format(os.path.split(item)[1]) # 附件别名
msgRoot.attach(att1)

try:
server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 发件人邮箱中的SMTP服务器,端口是25
server.login(sender, sender_pwd) # 括号中对应的是发件人邮箱账号、邮箱密码
server.sendmail(sender, receivers, msgRoot.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
server.quit() # 关闭连接
my_logger.info("邮件发送成功")
except smtplib.SMTPException as e:
my_logger.error("Error: 无法发送邮件")


if __name__ == '__main__':
SendEmail.send_email("subject", "具体内容见附件", mail_msg_type='plain',
mail_attach=["../test_result/html_report", "../test_result/log/log20220331.txt"])