csdn最牛最全的使用python自动发送邮件

使用python自动发送邮件

1、Python 自带的发送邮件功能

 在生成报告后我们希望框架能自动把报告发送到我们的邮箱中。和outlook,foxmail等邮件客户端一样,Python中发送邮件需要通过Email的smtp服务发送。

 首先需要确认用来发送邮件的邮箱是否启用了smtp服务,以126邮箱为例:

发送邮件分3步 

1. 编写邮件内容(Email邮件需要专门的MIME格式)

2. 组装Email头(发件人,收件人,主题)

3. 连接smtp服务器并发送邮件

 1.1 发送邮件基础实现

代码实现:

# -*- coding:utf-8 -*-
import smtplib  # 用于建立smtp连接
from email.mime.text import MIMEText  # 邮件需要专门的MIME格式

# 1.编写邮件内容,email邮件需要专门的MIME格式
msg =MIMEText("这是邮件正文:Hello.yin,this is a test mail", "plain", "utf-8")  # plain指普通文本格式邮件内容

# 2.组装Email头(发件人,收件人,主题)
msg['From'] = '[email protected]'  # 发件人
msg['To'] = '[email protected]'  # 收件人
msg['Subject'] = '这是邮件主题:Hello yin Api Test Report'  # 邮件主题

# 3.连接smtp服务器并发送邮件
smtp = smtplib.SMTP_SSL("smtp.126.com")  # smtp服务器地址,采用SSL模式
smtp.login('[email protected]', 'ROFAUSLTHKIIQJM')  # 如果使用126邮箱,需在设置中申请授权密码
smtp.sendmail('[email protected]', '[email protected]', msg.as_string())
smtp.quit()

输出结果:

1.2 中文邮件主题、HTML邮件内容,及附件 

实现代码:

# -*- coding:utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart  # 混合MIME格式,支持上传附件
from email.header import Header   # 用于使用中文邮件主题

# 1.编写邮件内容
with open("testReport.html", encoding='utf-8') as f:  # 打开html报告
    email_body = f.read()  # 读取报告内容

msg = MIMEMultipart()  # 混合MIME格式
msg.attach(MIMEText(email_body, 'html', 'utf-8'))  # 添加html格式邮件正文,会丢失css格式

# 2.组装email的头
msg['From'] = '[email protected]'  # 发件人
msg['To'] = '[email protected]'  # 收件人
msg['Subject'] = Header('接口测试报告', 'utf-8')  # 中文主题邮件,指定utf-8编码


# 3.构造附件1,传送到当前目录下的text.txt文件
att1 = MIMEText(open('testReport.html', 'rb').read(), 'base64', 'utf-8')  # 二进制格式打开
att1["Content-Type"] = "application/octet-stream"
att1["Content-Disposition"] = 'attachment; filename="report.html"'  # filename为邮件中附件显示的名字
msg.attach(att1)

# 连接smtp服务器并发送邮件
smtp = smtplib.SMTP_SSL("smtp.126.com")  # smtp服务器地址,使用SSL格式
smtp.login("[email protected]", "ROFAUSLTHKIIQJM")  # 用户名和密码
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
smtp.sendmail("[email protected]", "[email protected]", msg.as_string())  # 发送给另一个邮箱
smtp.quit()

输出结果:

 1.3 封装发送邮件办法

# -*- coding:utf-8 -*-
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from log.config import *


def send_email(report_file):
    msg = MIMEMultipart()  # 混合MIME格式
    msg.attach(MIMEText(open(report_file, encoding='utf-8').read(), 'utf-8'))  #  添加html格式邮件正文(会丢失css格式)
    msg['From'] = '[email protected]'  # 发件人
    msg['To'] = '[email protected]'  # 收件人
    msg['Subject'] = Header('接口测试报告', 'utf-8')  # 中文邮件主题,指定utf-8编码

    att1 = MIMEText(open(report_file, 'rb').read(), 'base64', 'utf-8')  # 二进制格式打开
    att1["Content-Type"] = 'application/octet-stream'
    att1["Content-Disposition"] = 'attachment; filename="testReport.html"'  # filename为邮件中附件显示的名字
    msg.attach(att1)

    try:
        smtp = smtplib.SMTP_SSL('smtp.126.com')  # smtp服务器地址 使用SSL模式
        smtp.login('[email protected]', 'ROFAUSLTHKIIQJM')  # 用户名和密码
        smtp.sendmail("[email protected]", "[email protected]", msg.as_string())
        smtp.sendmail("[email protected]", "[email protected]", msg.as_string())  # 发送给另一个邮箱
        logging.info("邮件发送完成!")
    except Exception as e:
        logging.error(str(e))
    finally:
        smtp.quit()

run_all.py中结束后发送邮件

# -*- coding:utf-8 -*-

import unittest
from HTMLTestRunner import HTMLTestRunner
from log.config import *
from test_send_mail_03 import send_email
logging.info("================================== 测试开始 ==================================")
suite = unittest.defaultTestLoader.discover("./")
with open("report.html", 'wb') as f:  # 改为with open 格式
    HTMLTestRunner(stream=f, title="Api Test", description="测试描述").run(suite)
send_email('report.html')  # 发送邮件
logging.info("================================== 测试结束 ==================================") 

猜你喜欢

转载自blog.csdn.net/m0_60054525/article/details/124915022