python使用SMTP发送邮件

    SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。SMTP协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。通过SMTP协议所指定的服务器,就可以把E-mail寄到收信人的服务器上了,整个过程只要几分钟。SMTP服务器则是遵循SMTP协议的发送邮件服务器,用来发送或中转发出的电子邮件

    在自动化测试过程中,当测试执行完成之后,需要自己找到测试报告的位置,并且发送到目标邮箱中,以便查看最终的测试结果。

    下面主要的内容是,将html的测试报告读取之后,放在邮件的内容中,并且把html测试报告放在附件中一起发送。

 1 #coding:utf-8
 2 
 3 import os,sys
 4 import smtplib
 5 import time
 6 from email.header import Header
 7 from email.mime.text import MIMEText
 8 from email.mime.multipart import MIMEMultipart
 9 
10 reportPath = os.path.join(os.getcwd(), 'report') # 测试报告的路径
11 # reportPath = os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])),'report')
12 
13 class SendMail(object):
14     def __init__(self,recver=None):
15         """接收邮件的人:list or tuple"""
16         if recver is None:
17             self.sendTo = ['xxxxx.@qq.com'] #收件人这个参数,可以是list,或者tulp,以便发送给多人
18         else:
19             self.sendTo = recver
20 
21     def get_report(self):# 该函数的作用是为了在测试报告的路径下找到最新的测试报告
22         dirs = os.listdir(reportPath)
23         dirs.sort()
24         newreportname = dirs[-1]
25         print('The new report name: {0}'.format(newreportname))
26         return newreportname #返回的是测试报告的名字
27 
28     def take_messages(self): # 该函数的目的是为了 准备发送邮件的的消息内容
29         newreport = self.get_report()
30         self.msg = MIMEMultipart()
31         self.msg['Subject'] = '测试报告主题' # 邮件的标题
32         self.msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
33 
34         with open(os.path.join(reportPath,newreport), 'rb') as f:
35             mailbody = f.read()# 读取测试报告的内容
36         html = MIMEText(mailbody,_subtype='html',_charset='utf-8') # 将测试报告的内容放在 邮件的正文当中
37         self.msg.attach(html) # 将html附加在msg里
38         
39         # html附件    下面是将测试报告放在附件中发送
40         att1 = MIMEText(mailbody, 'base64', 'gb2312')
41         att1["Content-Type"] = 'application/octet-stream'
42         att1["Content-Disposition"] = 'attachment; filename="TestReport.html"'#这里的filename可以任意写,写什么名字,附件的名字就是什么
43         self.msg.attach(att1)
44 
45     def send(self):
46         self.take_messages()
47         self.msg['from'] = 'xxxxx@163.com' # 发送邮件的人
48         smtp = smtplib.SMTP('smtp.163.com',25) # 连接服务器
49         smtp.login('xxxxx@163.com','xxxxxxx') # 登录的用户名和密码
50         smtp.sendmail(self.msg['from'], self.sendTo,self.msg.as_string()) # 发送邮件
51 smtp.close() 52 print('sendmail success') 53 54 if __name__ == '__main__': 55 sendMail = SendMail() 56 sendMail.send()


最终的发送结果:

 

posted @ 2016-08-11 21:33  小石头tester  阅读(1159)  评论(0编辑  收藏  举报