主代码如下:
点击查看代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/12/26 9:46 上午
# @Author : Ayden
# @Site :
# @File : send_email.py
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
import smtplib
import pathlib
from conf.setting import *
from common.log import Log
log = Log().log()
def send_mail(host="xxxxxx", port=None, title=None, send_files=None, content=None):
if not content:
title = "车联网接口自动化测试报告"
if not content:
content = " \n\n附件为车联网云平台接口自动化测试报告,请使用浏览器进行查看,访问地址为:\n" \
" http://{}:{}\n" \
"\n\n本邮件为自动发出,请勿回复".format(host, port)
mail_host = send_email["mail_host"]
mail_port = send_email["mail_port"]
mail_user = send_email["mail_user"]
mail_password = send_email["mail_pass"]
# log.debug("发件信息为:{}".format(send_email))
try:
msg = MIMEMultipart()
msg['Subject'] = title
msg['To'] = ",".join(receive_email)
print(msg['To'])
msg['From'] = mail_user
body = MIMEText(content, 'plain', 'utf-8')
if send_files:
#for send_file in send_files:
part_attach = MIMEApplication(open(send_files, 'rb').read()) # 打开附件
# 为附件命名
part_attach.add_header('Content-Disposition', 'attachment', filename=pathlib.Path(send_files).name)
# 添加附件
msg.attach(part_attach)
msg.attach(body)
smtp = smtplib.SMTP(mail_host, mail_port)
smtp.starttls()
smtp.login(mail_user, mail_password)
smtp.sendmail(mail_user, receive_email, msg.as_string())
# log.debug("邮件发送成功")
smtp.quit()
except Exception as e:
log.debug("邮件发送失败,原因是{}".format(e))
其中setting配置如下:
点击查看代码
# 发件人电子邮箱
send_email = {"mail_host": "smtp.163.com", "mail_port": 25, "mail_user": "api_auto_test@163.com",
"mail_pass": "XSJLZTQHSMAKPCMX"}
# 收件人电子邮箱
receive_email = ['api_auto_test@163.com', 'lizhaoyong94@163.com']
备注:以上日志模块请自行去除