SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
SMTP使用 sendmail 方法发送邮件,其语法为smtp.sendmail(sender,receiver,msg)
sender为发送人;
receiver为接收人;
msg是字符串,为发送的消息,即邮件(包括标题,发信人,收件人,邮件内容,附件等)
我们可以使用其他邮件服务商的 SMTP 访问,要先设置邮箱服务器,将邮件发送到该邮箱服务器,再由其进行代发,发送给接收人
以下为实例,将自动化测试生成的测试报告自动发送邮件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os
# 定义发送邮件(带附件)
def send_mail(file_new):
f = open(file_new,'rb')
# 读取测试报告
mail_body=f.read()
f.close()
# 发送邮箱服务器(QQ邮箱)
smtpserver = "smtp.qq.com"
# 发送人邮箱
sender = "XXX@qq.com"
# 发件人邮箱授权码(在QQ邮箱设置-账户里开启POP3/SMTP服务,获得16位授权码)
password = "XXX"
# 接收人邮箱
receiver = "XXX@163.com"
msg = MIMEMultipart()
# 邮件正文-测试报告
text = MIMEText(mail_body,"html","utf-8")
msg.attach(text)
# 邮件标题
msg["Subject"] = Header("自动化测试报告","utf-8")
# 附件内容-测试报告
msg_file = MIMEText(mail_body,"html","utf-8")
msg_file["Content-Type"] = "application/octet-stream"
# filename为邮件附件名称,可更改
msg_file["Content-Disposition"] = 'attachment; filename="AutoTestReport.html"'
msg.attach(msg_file)
try:
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(sender,password)
smtp.sendmail(sender,receiver,msg.as_string())
smtp.quit()
print "发送成功"
except:
print "发送失败"
# 查找出最新的测试报告
def new_report(testreport):
dirs = os.listdir(testreport)
dirs.sort()
newreportname = dirs[-1]
print "找到最新自动化测试报告,即将发送邮件"
file_new = os.path.join(testreport,newreportname)
return file_new
if __name__ == '__main__':
test_report = "XXX" # 为自动化测试报告存放的地址
new_report = new_report(test_report)
send_mail(new_report)