python邮件自动发送测试报告,看这篇文章就够了

Python SMTP发送邮件

  • SMTP(Simple Mail Transfer Protocol),简单的邮件传输协议。他是一组用于从源地址到目的地址传输邮件的规范,通过它来控制邮件的中转方式。SMTP协议属于 TCP/IP 协议簇,它帮组每台计算机再送中转信件时找到下一个目的地。SMTP服务器遵循 SMTP 协议的发送邮件服务器

开启SMTP

  • 这里我们以QQ邮箱为例,我们在邮箱设置 - 账户中找到开启服务,然后点击开启STMP
  • 然后设置一下客户端授权码
  • 发短信开启

在这里插入图片描述
然后我们可以通过python实现邮件发送了,下面是一个简单的例子

#! /usr/bin/python3
# -*- coding: UTF-8 -*-

import smtplib
import time
from email.mime.text import MIMEText
from email.header import Header


class TestMail(object):

    def __init__(self):
        self.mail_host = "smtp.qq.com"
        self.mail_user = "xxxxx@qq.com"
        self.mail_pass = ""  # 这里是QQ客户端授权密码

        self.sender = 'xxxxx@163.com' 
        self.receivers = ''

    def send_mail(self):
        body = 'Dear all:\n接口自动化测试报告如下:\n   测试用例集合:{}\n   运行结果:{}'.format('xxxx', 'xxxx')
        tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        message = MIMEText(body, 'plain', 'utf-8')
        message['From'] = self.mail_user
        message['To'] = self.receivers

        subject = '接口自动化报告测试'
        message['Subject'] = Header(subject + '_' + tm, 'utf-8')

        try:
            smtpObj = smtplib.SMTP()
            smtpObj = smtplib.SMTP_SSL(self.mail_host, 465)
            smtpObj.login(self.mail_user, self.mail_pass)
            smtpObj.sendmail(self.sender, self.receivers, message.as_string())
            print('send mail ok')
        except smtplib.SMTPException:
            print('send mail fail')


if __name__ == "__main__":
    send = TestMail()
    send.send_mail()

  • 然后通常在项目中,我们都是把邮箱的发送者和接受者以及一些邮件信息,单独放在config.yaml或者config.ini文件中进行配置化,下面我们来看看如何读取文件配置

读取配置

#! /usr/bin/python3
# -*- coding: UTF-8 -*-

[mail]
#发送邮件信息
mail_host = smtp.qq.com
mail_user = xxx@qq.com
mail_pass =            # 163客户端授权密码

sender = @qq.com
receivers = 

  • 读取配置
#! /usr/bin/python3
# -*- coding: UTF-8 -*-

import smtplib
import time
from pathlib import Path
from email.mime.text import MIMEText
from email.header import Header

from configparser import ConfigParser


class TestMail(object):

    def __init__(self):
        self.config = ConfigParser()
        self.conf_path = str(Path('config.ini').absolute())  # 读取绝对路径

        self.config.read(self.conf_path, encoding='utf-8')

    def send_mail(self):
        body = 'Dear all:\nDEMO 接口自动化测试报告:\n   测试用例集合:{}\n   运行结果:{}'.format('xxxx', 'xxxx')
        tm = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        message = MIMEText(body, 'plain', 'utf-8')
        message['From'] = self.config.get('mail', 'sender')
        message['To'] = self.config.get('mail', 'receivers')

        subject = '接口自动化测试报告'
        message['Subject'] = Header(subject + '_' + tm, 'utf-8')

        try:
            smtpObj = smtplib.SMTP()
            smtpObj = smtplib.SMTP_SSL(self.config.get('mail', 'mail_host'), 465)
            smtpObj.login(self.config.get('mail', 'mail_user'), self.config.get('mail', 'mail_pass'))
            smtpObj.sendmail(self.config.get('mail', 'sender'), self.config.get('mail', 'receivers'), message.as_string())
            print('send mail ok')
        except smtplib.SMTPException:
            print('send mail fail')


if __name__ == "__main__":
    send = TestMail()
    send.send_mail()

发送邮件带附件

  • 通常我们发邮件有时会需要发送附件,比如测试报告,贴代码
#! /usr/bin/python3
# -*- coding: UTF-8 -*-

import os
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header


def send_kindle():
    mail_host = "smtp.qq.com"
    mail_user = "@qq.com"
    mail_pass = ""

    sender = '@qq.com'
    receivers = '@kindle.cn'

    message = MIMEMultipart()
    message['From'] = mail_user
    message['To'] = receivers
    subject = '{}'.format(filename)
    message['Subject'] = Header(subject, 'utf-8')

    message.attach(MIMEText('{}'.format(filename), 'plain', 'utf-8'))

    att1 = MIMEText(open('/Users/Documents/book/{}'.format(filename), 'rb').read(), 'base64', 'utf-8')
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] = 'attachment; filename="book.mobi"'
    message.attach(att1)

    try:
        smtpObj = smtplib.SMTP_SSL(mail_host, 465)
        smtpObj.login(mail_user, mail_pass)
        smtpObj.sendmail(sender, receivers, message.as_string())
        print("发送成功")
    except smtplib.SMTPException:
        print("Error: 发送失败")


if __name__ == '__main__':
    filename = input("请输入您要发送的附件名称")
    os.path.split(filename)
    send_kindle()

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

七月的小尾巴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值