import requests
from exchangelib import DELEGATE, Account, Credentials, Message, Mailbox, HTMLBody, FileAttachment
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 忽略requests证书警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
#此句用来消除ssl证书错误,exchange使用自签证书需加上
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter
def Email(to, subject, body, attachmentspath=None):
creds = Credentials(
username='********', # 账号
password='********' # 密码
)
account = Account(
primary_smtp_address='************@qq.com', # 发送方邮箱地址
credentials=creds,
autodiscover=True,
access_type=DELEGATE
)
m = Message(
account=account,
subject=subject,
body=HTMLBody(body),
to_recipients=[Mailbox(email_address=to)]
)
# 添加附件
attachments = []
with open(r"{}/report.xlsx".format(attachmentspath), 'rb') as f:
content = f.read()
attachments.append(('report.xlsx', content))
with open(r"{}/report.txt".format(attachmentspath), 'rb') as f:
content = f.read()
attachments.append(('report.txt', content))
with open(r"{}/Consolo Log.txt".format(attachmentspath), 'rb') as f:
content = f.read()
attachments.append(('Consolo Log.txt', content))
with open(r"{}/calibration.txt".format(attachmentspath), 'rb') as f:
content = f.read()
attachments.append(('calibration.txt', content))
# 附加文件
for attachment_name, attachment_content in attachments or []:
file = FileAttachment(name=attachment_name, content=attachment_content)
m.attach(file)
m.send_and_save()
if __name__ =='__main__':
body='项目名称:E43<br/>' '测试用例:CAN应用<br/>' '测试结果:用例总数:{}|已测用例数:{}|OK:{}|NG:{}'.format(2, 2, 1, 1)
# "接收方的邮箱", "邮件标题", "邮件内容", "报告路径"
Email("*********@qq.com", "测试报告", body=body, attachmentspath=r'E:\report')
运行结果
D:\Python3.8.6\python.exe D:/PythonWorkSpace/chenbang/Send_mail2.py
Process finished with exit code 0
运行截图
备注
1、此方法是基于exchange方式登录的邮箱,不是基于smtp?
2、可以添加多个附件
3、四处地方需要修改,发送方邮件、账户、密码、接受方邮件
|