在自动化测试结束后,我们往往需求把测试结果通过邮件发送给团队成员。Python语言如何实现自动发送邮件?请看:

方式一:

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

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

实例:import smtplib

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class SendEmail():
    global send_user
    global smtpserver
    global password
    global sendfile
    # 发送邮箱服务器
    smtpserver = 'smtp.163.com'
    # 发送邮箱/密码
    send_user = "###@163.com"
    password = '###'
    # 发送的附件
    sendfile = open("附件路径",'rb').read()

    def send_email(self,receiver_list, sub):
        user = "coco"+"<"+send_user+">"
        att = MIMEText(sendfile,'base64','utf-8')
        att['Content-Type'] = 'application/octet-stream'
        att['Content-Disposition'] = 'attachment;filename="report.html"'

        message = MIMEMultipart('related')
        message['Subject'] = sub
        message.attach(att)
        message['From'] = send_user
        message['To'] = ";".join(receiver_list)

        server = smtplib.SMTP()
        server.connect(smtpserver)
        server.login(send_user, password)
        server.sendmail(send_user, receiver_list, message.as_string())
        server.quit()

if __name__ == "__main__":
    smtpsender = SendEmail()
    sub = "python测试报告"
    receiver_list = ['receiver1@qq.com','receiver2@qq.com']

    smtpsender.send_email(receiver_list, sub)

方式二:yagmail 实现发邮件

yagmail 可以更简单的来实现自动发邮件功能。

github项目地址: https://github.com/kootenpv/yagmail

先安装yagmail 库,在cmd命令环境下 :pip install yagmail

实例:

import yagmail

# 链接邮箱服务器
yag = yagmail.SMTP(user="###@163.com",password="###",host="smtp.163.com")

# 邮件发送内容
content = "邮件正文,test......."

# 发送邮件
yag.send(receiver="###@163.com",subject="测试邮件",content)

  发送给多人,用list存放收件人邮箱:

yag.send(["###@163.com","###@qq.com"],subject="测试邮件",content)

  发送附件

yag.send("###@163.com",”subject",content,["附件路径1","附件路径2"])