博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【自动化测试】发送邮件 SMTP
阅读量:6899 次
发布时间:2019-06-27

本文共 5591 字,大约阅读时间需要 18 分钟。


如何使用Python将生成的测试报告以邮件附件的形式进行发送呢?

一、概要

SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。

python的smtplib提供了一种很方便的途径发送电子邮件,它对smtp协议进行了简单的封装。

Python对SMTP支持有smtplibemail两个模块。其中email负责构造邮件,smtplib则负责发送邮件。

来理一理Python发送一个未知MIME类型的文件附件基本思路:

0、前提:导入邮件发送模块        from email.mime.text import MIMEText        from email.mime.multipart import MIMEMultipart        import smtplib1、构造MIMEMultipart对象作为根容器2、构造MIMEText对象作为邮件显示内容并附加到根容器    a、读入文件内容并格式化    b、设置附件头3、设置根容器属性4、得到格式化后的完整文本5、用smtp发送邮件6、封装成sendEmail类。

二、邮件发送要素

同时想想我们要发送邮件的几个要素:

1、服务器。以QQ邮箱举例,则为smtp.qq.com2、端口号。有465和587,请使用5873、发送者。4、密码。密码总不能直接写在文件里吧?哈哈,这里需要使用qq邮箱获取授权码。5、收件人。(可能还不止一个)6、发送邮件的主题subject。7、邮件文本内容。8、附件。

因为之前写过如何读取.ini配置文件,所以此部分,将发送邮件的一些要素放在了配置文件中,配置文件如下:

clipboard.png

对应读取配置文件脚本为:(readConfig.py部分)

import osimport configparser# configcur_path = os.path.dirname(os.path.relpath(__file__))configPath = os.path.join(cur_path,'config.ini')conf = configparser.ConfigParser()conf.read(configPath)def get_smtpServer(smtpServer):    smtp_server = conf.get('email',smtpServer)    return smtp_server# ......

三、邮件部分

构建MIMEMultipart()邮件根容器对象后,需要借助根容器来定义邮件的各个要素,比如邮件主题subject、发送人from、接收人to、邮件正文body、邮件附件等。

如何给邮件定主题、收发人呢?

# 构建根容器msg = MIMEMultipart()# 邮件主题、发送人、收件人、内容,此部分可以来自配置文件,也可以直接填入msg['Subject'] = self.mail_subject  # u'自动化测试报告'msg['from'] = self.mail_sendermsg['to'] = self.mail_pwd

如何定义邮件正文body部分呢?

# 邮件正文部分body,1、可以用HTML自己自定义body内容;2、读取其他文件的内容为body# body = "您好,

这里是使用Python登录邮箱,并发送附件的测试<\p>"with open(reportFile,'r',encoding='UTF-8') as f: body = f.read()msg.attach(MIMEText(_text=body, _subtype='html', _charset='utf-8')) # _charset 是指Content_type的类型

如何给邮件添加附件呢?

# 添加附件attachment = MIMEText(_text=open(reportFile, 'rb').read(), _subtype='base64',_charset= 'utf-8')attachment['Content-Type'] = 'application/octet-stream'attachment['Content-Disposition'] = 'attachment;filename = "result.html"'msg.attach(attachment)

如何发送?

发送四部曲:取得服务器连接、再登录邮箱、发送邮件、退出。

大致如下啦:

try:      smtp = smtplib.SMTP_SSL(host=self.mail_smtpserver, port=self.mail_port)  # 继承自SMTPexcept:      smtp = smtplib.SMTP()      smtp.connect(self.mail_smtpserver, self.mail_port)# smtp.set_debuglevel(1)# 创建安全连接,加密SMTPsmtp.starttls()     # Puts the connection to the SMTP server into TLS mode.# 用户名和密码smtp.login(user=self.mail_sender, password=self.mail_pwd)# 函数:sendmail(self, from_addr, to_addrs, msg, mail_options=[],rcpt_options=[]):smtp.sendmail(self.mail_sender, self.mail_receiverList, msg.as_string())smtp.quit()

在里面添加了一句smtp.starttls()。这一句是用来加密SMTP会话,保证邮件安全发送不被窃听的。

在创建完SMTP对象后,立刻调用starttls()方法即可。
其实整个下来邮件发送模块也就完成了。

四、问题

在这个过程中有遇见几个问题,也贴上来跟大家一起分享一下。

  • 抛错535
    抛错:smtplib.SMTPAuthenticationError: (535, b'Error: xc7xebxcaxb9xd3xc3xcaxdaxc8xa8xc2xebxb5xc7xc2xbcxa1xa3xcfxeaxc7xe9xc7xebxbfxb4: ')
    解决办法:点击最后的链接,其实是因为授权码问题
  • 替换授权码后继续报错,535
    解决办法:替换端口。因为qq邮箱ssl协议端口有两个:465/587。
  • 报错:smtplib.SMTPAuthenticationError: (530, b'Must issue a STARTTLS command first.')
    解决方法:在login()之前,添加一句:smtp.starttls()

五、代码all

下面贴上整个文件,这个文件是依赖于其他文件的的,所以仅供参考,但是方法是一样的。

import smtplibfrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom email.mime.base import MIMEBaseclass SendEmail(object):    '''    发送邮件模块封装,属性均从config.ini文件获得    '''    def __init__(self, smtpServer, mailPort, mailSender, mailPwd, mailtoList, mailSubject):          self.mail_smtpserver = smtpServer        self.mail_port = mailPort        self.mail_sender = mailSender        self.mail_pwd = mailPwd        # 接收邮件列表        self.mail_receiverList = mailtoList        self.mail_subject = mailSubject        # self.mail_content = mailContent    def sendFile(self, reportFile):        '''        发送各种类型的附件        '''        # 构建根容器        msg = MIMEMultipart()                # 邮件正文部分body,1、可以用HTML自己自定义body内容;2、读取其他文件的内容为body        # body = "您好,

这里是使用Python登录邮箱,并发送附件的测试<\p>" with open(reportFile,'r',encoding='UTF-8') as f: body = f.read() # _charset 是指Content_type的类型 msg.attach(MIMEText(_text=body, _subtype='html', _charset='utf-8')) # 邮件主题、发送人、收件人、内容 msg['Subject'] = self.mail_subject # u'自动化测试报告' msg['from'] = self.mail_sender msg['to'] = self.mail_pwd # 添加附件 attachment = MIMEText(_text=open(reportFile, 'rb').read(), _subtype='base64',_charset= 'utf-8') attachment['Content-Type'] = 'application/octet-stream' attachment['Content-Disposition'] = 'attachment;filename = "result.html"' msg.attach(attachment) try: smtp = smtplib.SMTP_SSL(host=self.mail_smtpserver, port=self.mail_port) # 继承自SMTP except: smtp = smtplib.SMTP() smtp.connect(self.mail_smtpserver, self.mail_port) # smtp.set_debuglevel(1) # 创建安全连接,加密SMTP smtp.starttls() # Puts the connection to the SMTP server into TLS mode. # 用户名和密码 smtp.login(user=self.mail_sender, password=self.mail_pwd) # 函数:sendmail(self, from_addr, to_addrs, msg, mail_options=[],rcpt_options=[]): smtp.sendmail(self.mail_sender, self.mail_receiverList, msg.as_string()) smtp.quit()# 调试代码if __name__ == "__main__": mail_smtpserver = 'smtp.qq.com' mail_port = 587 mail_sender = '@qq.com' mail_pwd = '' mail_receiverList = ['@qq.com', '@163.com'] mail_subject = u'自动化测试报告' s = SendEmail(mail_smtpserver, mail_port, mail_sender, mail_pwd, mail_receiverList, mail_subject) s.sendFile('F:\Python_project\PythonLearnning_2018\send_email\sendEmail_Test.html.tar.gz') print('--- test end --- ')


如果觉得文章有丢丢用处,动动小指,点个赞吧!

如果哪里写的有问题,或者有更好的方式,cue我一下
❤ thanks for watching, keep on updating...

转载地址:http://eycdl.baihongyu.com/

你可能感兴趣的文章
中国物流能送到四海八荒,菜鸟年度排行榜告诉你都去了哪些地方
查看>>
从业界良心到疲态尽显 Netflix到底中了什么降头?
查看>>
OpenStack消亡?在企业落地为什么越来越难
查看>>
GitHub因Memcached漏洞遭遇DDoS攻击,专家称攻击会持续发生!
查看>>
湖南郴州与新疆托克逊特色年货节开幕
查看>>
快手音乐人计划:音乐人可以靠作品赚到真金白银
查看>>
使用Python一年多了,总结八个好用的Python爬虫技巧
查看>>
无人船成下一个全球研发热点,参与行业标准的「云洲智能」要做海洋上的&quot;SpaceX&quot;...
查看>>
13种数据分析思维
查看>>
3分钟搞掂Set集合
查看>>
如果再有人问你分布式 ID,这篇文章丢给他
查看>>
90% New Grads 都懵逼的面试轮次,这些应对“骚操作”请收好
查看>>
重磅 | PyTorch 0.4.0和官方升级指南,支持Windows
查看>>
http状态码是什么,有什么用,在哪里查看,分别代表什么意思?
查看>>
应用迁移至 Android P 操作指南
查看>>
用 CoordinatorLayout 处理滚动
查看>>
网络七层模型与四层模型区别
查看>>
新版 iText 集成腾讯、百度、Google 三引擎
查看>>
那些年,遇到的乱码
查看>>
用CSS来计数
查看>>