SendEmail.py
2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from commons.Logging import Logger
log=Logger()
def send_email_text():
# 1. 编写邮件内容(Email邮件需要专门的MIME格式)
msg = MIMEText('this is a test email', 'plain', 'utf-8')
# 2. 组装Email头(发件人,收件人,主题)
msg['From'] = 'autotest@diligrp.com' # 发件人
msg['To'] = 'lixi@diligrp.com' # 收件人
msg['Subject'] = 'Api Test Report' # 邮件主题
# 3. 连接smtp服务器并发送邮件
smtp = smtplib.SMTP_SSL('smtp.exmail.qq.com')
smtp.login('autotest@diligrp.com', 'MvkuGGCfMtAdbJvE')
smtp.sendmail("autotest@diligrp.com", "lixi@diligrp.com", msg.as_string())
smtp.quit()
def send_email(send_file,send_to=["lixi@diligrp.com"]):
log_path=os.path.dirname(os.path.dirname(__file__))
log_path=log_path+"/report/test.log"
send_msg=(",".join(str(i) for i in send_to))
msg = MIMEMultipart() # 混合MIME格式
msg['From'] = 'autotest@diligrp.com' # 发件人
msg['To'] = send_msg # 收件人
msg['Subject'] = Header('接口测试报告', 'utf-8') # 中文邮件主题,指定utf-8编码
text = MIMEText('this is a test email', 'plain', 'utf-8')
msg.attach(MIMEText(open(send_file,'rb' ).read(), 'html', 'utf-8'))
att1 = MIMEText(open(send_file, 'rb').read(), 'base64', 'utf-8')
att1["Content-Disposition"] = 'attachment; filename="report.html"'
att2 = MIMEText(open(log_path, 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="test.log"'
msg.attach(text)
msg.attach(att1)
msg.attach(att2)
#一下发送日志不会在test.log上,因为提前msg.attach了
log.info("发送邮件")
try:
smtp = smtplib.SMTP_SSL('smtp.exmail.qq.com') # smtp服务器地址 使用SSL模式
re=smtp.login('autotest@diligrp.com', 'MvkuGGCfMtAdbJvE') # 用户名和密码
smtp.sendmail("autotest@diligrp.com", send_to, msg.as_string())
print(re)
except Exception as e:
log.error(str(e))
print(e)
finally:
smtp.quit()
log.info("邮件发送完毕")