前置知识:
1.什么是SMTP
SMTP:简单邮件传输协议
SMTP:Simple Mail Transfer Protocol)
SMTP 是一种提供可靠且有效电子邮件传输的协议。 SMTP 是建模在 FTP 文件传输服务上的一种邮件服务,主要用于传输系统之间的邮件信息并提供来信有关的通知
2.在python中使用SMTP 需要的准备工作
- 在发邮件方开启 SMTP协议 且获取提供的动态密码
- python中需要掌握两个模块的用法,smtplib和email,这两个模块是自带的无需另外导入可直接使用,在这里需要了解的是 以下包的用法
import smtplib #导入smtplib库 from email.mime.text import MIMEText # 导入发送正文 from email.header import Header #导入 从email包引入Header()方法,是用来构建邮件头 from email.mime.multipart import MIMEMultipart #发送多个部分 from email.mime.application import MIMEApplication # 发送附件
3.smtplib 简单介绍
smtp = smtplib.SMTP() #创建 SMTP对象 smtp.connect(smtpserver) #连接SMTP服务器 smtp.login(username,passowrd) #使用账号和密码登录 smtp.sendmail(sender,receiver,msg.as_string()) #通过发送方和接收方以及信息进行发送
4.话不多说直接开干
import os
import time
import smtplib
from email.mime.text import MIMEText # 发送正文
from email.header import Header # 从email包引入Header()方法,是用来构建邮件头
from email.mime.multipart import MIMEMultipart #发送多个部分
from email.mime.application import MIMEApplication # 发送附件
class SendTestReportByAttach(object):
def getReportPath(self):
'''
获取最新测试报告文件路径
'''
lists = os.listdir('Report')
lists.sort(key=lambda fn: os.path.getmtime('Report'+"\"+fn)
if not os.path.isdir("Report" + "\" + fn) else 0)
return os.path.join("Report",lists[-1])
def sendTestReportAttAcher(self):
sender = 'xxx@126.com'
receiver = 'xxx@qq.com'
t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
subject = '自动化测试报告' + t
smtpserver = 'smtp.126.com'
username = "xxx@126.com"
passowrd = "xxxx"
msg = MIMEMultipart() # 邮件体
msg['from'] = sender
msg['to'] = receiver
msg['Subject'] = Header(subject+"_"+t,'utf-8')
content = """
test over!!
get Report……
get Report over……
The report is sended!!
"""
email_body = MIMEText(content,'plain','utf-8')
msg.attach(email_body) #写入正文
newsFile = self.getReportPath() # 构建附件
att = MIMEApplication(open(newsFile,"rb").read()) # 打开附件
att.add_header("Content-Disposition", "attachment",filename='测试报告.html')
msg.attach(att) #附加上附件
try:
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username,passowrd)
smtp.sendmail(sender,receiver,msg.as_string())
except Exception as e:
print(e)
print('send mail fail')
else:
print('send mail ok')
finally:
smtp.quit()
if __name__ == "__main__":
sendTestReportByAttach = SendTestReportByAttach()
sendTestReportByAttach.sendTestReportAttAcher()
运行结果:



