#!/usr/bin/env/python
# -*- coding: utf-8 -*-
# @Time : 2018/11/19 9:56
# @Author : ChenAdong
# @Email : aiswell@foxmail.com import smtplib s = smtplib.SMTP("smtp.qq.com", port=25)
tolist = ["xxx@163.com"] # 收件人列表
s.set_debuglevel(1)
msg = """\\
From:apiTestRobot<xxx@qq.com>
To:xxx@163.com # 填写收件邮箱
Subject:test THIS IS A TEST test dfdafdaf
THIS IS A TEST test dfdafdaf
THIS IS A TEST test dfdafdaf
THIS IS A TEST test dfdafdaf
"""
s.login("xxx@qq.com", "xxx")
s.sendmail("xxx@qq.com", "xxx@163.com", msg) # f填写发件邮箱和收件邮箱地址
s.quit()
注意事项:
这里的密码是授权码,需要打开QQ邮箱内的对应服务,然后生成授权码(可以当做密码用)
如图:
效果图:
* 上面是一个入门版本,下面介绍一个高级一点的版本
#!/usr/bin/env/python
# -*- coding: utf-8 -*-
# @Time : 2018/11/19 9:56
# @Email : aiswell@foxmail.com import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
import time def mymail(result):
"""
:param result: str
:return:
"""
s = smtplib.SMTP("smtp.qq.com", port=25)
tolist = ["xxx@163.com", "xxx@xxx.com", ]
s.set_debuglevel(1)
msg = MIMEText(result, "plain", "utf-8")
msg["From"] = formataddr(["xxx", "xxx@qq.com"])
msg["To"] = formataddr(["xxx", "xxxx@163.com"])
_time = time.strftime("%Y-%m-%d", time.localtime())
msg["Subject"] = "%s 接口测试结果" % str(_time)
s.login("xxx@qq.com", "xxx") # 前面是邮箱地址,后面是授权码
s.sendmail("xxx@qq.com", tolist, msg.as_string()) # 注意一定要用as_string方法,不然会报错
s.quit() if __name__ == "__main__":
log_path = "..//log//" + time.strftime("%Y-%m-%d", time.localtime()) + ".txt"
with open(log_path, "r") as result:
r = result.readlines()
str_result = ""
for line in r:
r_tem = "\r\n\t%s" % line
str_result = str_result + r_tem
print mymail(str_result)
但是在实际应用中,可能需要美观一点,可以发送html格式:
with open("./2018-11-21.html", "r") as f:
# content = f.readlines()
content = f.read()
如上,如果使用注释掉的方法发送的话,会出现乱码;正确的方式是f.read()
然后,msg = MIME.text(content, "html", "utf-8")
sendmail(from_addr, to_addr, msg.as_string())
需要注意的是,还是msg.as_string()
下面是发送的html文件样例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<table border="1" cellspacing="0" bgcolor="#e6e6fa">
<tr>
<td>时间</td>
<td>序列</td>
<td>用例名</td>
<td>status_code</td>
<td>msg</td>
<td>断言</td>
</tr>
<tr>
<td>555</td>
<td>fdafadf</td>
<td>fdafdafdafdafdafdafda</td>
<td>statffdafdafdafus_code</td>
<td>msg</td>
<td>断fdafdafda555454564546545645645言</td>
</tr>
</table>
</body>
</html>