要在Python中发送测试报告邮件,可以使用smtplibemail库来实现。以下是简单的代码,以qq邮箱为例,注:邮箱密码得事先申请,如下:

python中发送测试报告邮件_邮件发送

python中发送测试报告邮件_邮件发送_02

先开启服务,之后再申请(需绑定一手机号)

python中发送测试报告邮件_发送邮件_03

代码如下:

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from untitled.API_Auto3.tools.project_path import * #此处是自己写的一个路径获取类

class sendEmail:
    def send_email(self,sender_email, sender_password, receiver_email, subject, body, attachment_path=None):
        try:
            # 设置邮件服务器和端口(这里以QQ邮箱为例)
            smtp_server = 'smtp.qq.com'
            smtp_port = 587

            # 邮件内容设置
            msg = MIMEMultipart()#创建实例:多个部分
            msg['From'] = sender_email
            msg['To'] = receiver_email
            msg['Subject'] = Header(subject, 'utf-8')

            # 邮件正文
            msg.attach(MIMEText(body, 'plain', 'utf-8'))

            # 附件,只能发一个附件
            if attachment_path:
                with open(attachment_path, 'rb') as f:
                    attachment = MIMEText(f.read(), 'base64', 'utf-8')
                    attachment['Content-Type'] = 'application/octet-stream'
                    attachment.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', attachment_path.split('/')[-1]))
                    msg.attach(attachment)

            # 建立SMTP连接
            smtp = smtplib.SMTP(smtp_server, smtp_port)#如果使用SMTP_SSL()方法时,注意smtp_port的修改
            smtp.starttls()  # 使用TLS加密连接

            # 登录邮箱
            smtp.login(sender_email, sender_password)

            # 发送邮件
            smtp.sendmail(sender_email, receiver_email, msg.as_string())

            # 关闭SMTP连接
            smtp.quit()

            print("邮件发送成功")
        except Exception as e:
            print("邮件发送失败:", e)

if __name__ == "__main__":
    import time
    sender_email = 'your_sender_email@qq.com'
    sender_password = 'your_sender_email_password'
    receiver_email = 'receiver@example.com'
    subject = time.strftime('%Y-%m-%d_%H_%M_%S')+'测试报告'
    body = '该文件为测试报告,请查收!'
    attachment_path =test_report_path   # 如果有附件,请提供附件的路径

    a =sendEmail()
    a.send_email(sender_email, sender_password, receiver_email, subject, body, attachment_path)