【自动化测试】发送邮件 SMTP


如何使用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 smtplib
1、构造MIMEMultipart对象作为根容器
2、构造MIMEText对象作为邮件显示内容并附加到根容器
    a、读入文件内容并格式化
    b、设置附件头
3、设置根容器属性
4、得到格式化后的完整文本
5、用smtp发送邮件
6、封装成sendEmail类。

二、邮件发送要素

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

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

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

clipboard.png

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

import os
import configparser

# config
cur_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_sender
msg['to'] = self.mail_pwd
如何定义邮件正文body部分呢?
# 邮件正文部分body,1、可以用HTML自己自定义body内容;2、读取其他文件的内容为body
# body = "您好,<p>这里是使用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)  # 继承自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()

在里面添加了一句smtp.starttls()。这一句是用来加密SMTP会话,保证邮件安全发送不被窃听的。
在创建完SMTP对象后,立刻调用starttls()方法即可。
其实整个下来邮件发送模块也就完成了。

四、问题

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

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

五、代码all

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

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase

class 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 = "您好,<p>这里是使用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...

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值