python 发送带有附件的邮件

在selenium运行完成,想要把测试报告和截图发送指定的邮箱,需要先把测试报告和截图文件夹打包成压缩文件然后一起发送,下面就是代码:

1.压缩文件

import os,zipfile

#压缩文件
def compression():
    try:
        fantasy_zip = zipfile.ZipFile(压缩文件存放路径,‘w‘)
        for folder,subfolders,files in os.walk(测试报告文件夹路径):
            for file in files:
                fantasy_zip.wirte(os.path.join(folder,file),
                                  os.path.relpath(os.path.join(folder,file),测试报告文件夹路径),
                                  compress_type=zipfile.ZIP_DEFLATED)
    except:
        logger.warning(‘压缩文件失败‘)
        raise

2.添加到邮件附件

import mimetype,os
from email.mime.base import MIMEBase
from email import encoders

def annex():
    try:
        data = open(压缩文件名,‘rb‘)
        ctype,encoding = mimetype.guess_type(压缩文件名)
        if ctype is None or encoding is not None:
            ctype = ‘application/x-zip-compressed‘
        maintype,subtype = ctype.split(‘/‘,1)
        file_msg = MIMEBase(maintype,subtype)
        file_msg.set_payload(data.read())
        data.close()
        encoders.encode_base64(file_msg)
        basename = os.path.basename(压缩文件名)
        file_msg.add_header(‘Content-Disposition‘, ‘attachment‘, filename=basename)
        return file_mag
    except:
        logger.warning(‘添加文件失败!‘)
        raise

3.构造邮件模板

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

def data():
    """邮件内容"""
    # 报告位置进行按时间排序,返回一个最新的测试报告文件,目录格式和保存测试报告的一致
    report_lists = os.listdir(report[‘report_file_dir‘])
    report_lists.sort(key=lambda fn: os.path.getmtime(report[‘report_file_dir‘] + ‘\\‘ + fn))
    report_new_file = os.path.join(report[‘report_file_dir‘], report_lists[-1])
    # 读取最新报告的内容
    f = open(report_new_file, ‘rb‘)
    main_body = f.read()
    f.close()
    try:
        self.compression()
        message_annex = MIMEMultipart()
        annex = self.annex()
        # """构建根容器"""
        test = MIMEText(main_body,‘html‘,‘utf-8‘)
        message_annex[‘From‘] = "{}".format(email[‘username‘])
        message_annex[‘To‘]=",".join(email[‘receivers‘])
        message_annex[‘Subject‘]="OMS 自动化用例测试报告"

        # """将文本和附件内容添加到邮件"""
        message_annex.attach(annex)
        message_annex.attach(test)
        fullTest = message_annex.as_string()
        return fullTest
    except:
        logger.error(‘邮件内容错误!!!‘)
        raise

4.发送邮件

import os,time,smtplib   

def send_eamil():
    try:
        message = self.data()
        smtpObj=smtplib.SMTP_SSL(email[‘host‘],465)
        smtpObj.login(email[‘username‘],email[‘password‘])
        flag = True
        while flag:
            try:
                smtpObj.sendmail(email[‘username‘],email[‘receivers‘],message)
                smtpObj.quit()
                flag = False
            except:
                logger.info(‘发送失败!!!正在重新发送...‘)
                time.sleep(2)
                continue
        logger.info(‘邮件发送成功‘)
    except:
        logger.warning(‘配置有误!!!‘)
        raise

整合起来代码如下

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import smtplib,time,os,zipfile,mimetypes

class SendEmail():
    """发送邮件"""

    def send_eamil(self):
        try:
            message = self.data()
            smtpObj=smtplib.SMTP_SSL(email[‘host‘],465)
            smtpObj.login(email[‘username‘],email[‘password‘])
            flag = True
            while flag:
                try:
                    smtpObj.sendmail(email[‘username‘],email[‘receivers‘],message)
                    smtpObj.quit()
                    flag = False
                except:
                    logger.info(‘发送失败!!!正在重新发送...‘)
                    time.sleep(2)
                    continue
            logger.info(‘邮件发送成功‘)
        except:
            logger.warning(‘配置有误!!!‘)
            raise

    def data(self):
        """邮件内容"""
        # 报告位置进行按时间排序,返回一个最新的测试报告文件,目录格式和保存测试报告的一致
        report_lists = os.listdir(report[‘report_file_dir‘])
        report_lists.sort(key=lambda fn: os.path.getmtime(report[‘report_file_dir‘] + ‘\\‘ + fn))
        report_new_file = os.path.join(report[‘report_file_dir‘], report_lists[-1])
        # 读取最新报告的内容
        f = open(report_new_file, ‘rb‘)
        main_body = f.read()
        f.close()
        try:
            self.compression()
            message_annex = MIMEMultipart()
            annex = self.annex()

            # """构建根容器"""
            test = MIMEText(main_body,‘html‘,‘utf-8‘)
            message_annex[‘From‘] = "{}".format(email[‘username‘])
            message_annex[‘To‘]=",".join(email[‘receivers‘])
            message_annex[‘Subject‘]="OMS 自动化用例测试报告"

            # """将文本和附件内容添加到邮件"""
            message_annex.attach(annex)
            message_annex.attach(test)
            fullTest = message_annex.as_string()
            return fullTest
        except:
            logger.error(‘邮件内容错误!!!‘)
            raise

    def compression(self):
        """将文件夹压缩为zip"""
        try:
            fantasy_zip = zipfile.ZipFile(report[‘zip_name‘], ‘w‘)
            for folder,subfolders,files in os.walk(report[‘report_file_dir‘]):
                for file in files:
                    fantasy_zip.write(os.path.join(folder, file),
                                      os.path.relpath(os.path.join(folder, file), report[‘report_file_dir‘]),
                                      compress_type=zipfile.ZIP_DEFLATED)
            fantasy_zip.close()
        except:
            logger.warning(‘文件夹压缩失败‘)
            raise

    def annex(self):
        """将zip添加附件"""
        try:
            data = open(report[‘zip_name‘], ‘rb‘)
            ctype, encoding = mimetypes.guess_type(report[‘zip_name‘])
            if ctype is None or encoding is not None:
                ctype = ‘application/x-zip-compressed‘
            maintype, subtype = ctype.split(‘/‘, 1)
            file_msg = MIMEBase(maintype, subtype)
            file_msg.set_payload(data.read())
            data.close()
            encoders.encode_base64(file_msg)
            basename = os.path.basename(report[‘zip_name‘])
            file_msg.add_header(‘Content-Disposition‘, ‘attachment‘, filename=basename)
            return file_msg
        except:
            logger.warning(‘文件添加失败‘)
            raise

原文地址:https://www.cnblogs.com/shiyuheng/p/10114087.html

时间: 2024-10-01 03:28:11

python 发送带有附件的邮件的相关文章

Android在发送带有附件的邮件

准备好工作了-下载最新的版本号JMail https://java.net/projects/javamail/pages/Home#Download_JavaMail_1.5.2_Release http://www.oracle.com/technetwork/java/javase/downloads/index-135046.html 在android上发送邮件方式: 第一种:借助GMail APPclient.缺点是必须使用GMail帐号,有点是比較方便 不须要写非常多代码.可是不是非

Java Mail 发送带有附件的邮件

1.小编用的是163邮箱发送邮件,所以要先登录163邮箱开启POP3/SMTP/IMAP服务方法: 2.下载所需的java-mail 包 https://maven.java.net/content/repositories/releases/com/sun/mail/javax.mail/ 3.贴上代码 package javamail; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; impor

【Mail】JavaMail发送带附件的邮件

上一篇讲了使用JavaMail发送普通邮件([Mail]JavaMail介绍及发送邮件(一)),本例讲发送复杂的邮件(带有附件的邮件) 生成一封复杂的邮件 新建一个JavaWeb的Maven工程,引入javamail.jar包,maven引用如下: 1 <!-- javamail --> 2 <dependency> 3 <groupId>javax.mail</groupId> 4 <artifactId>mail</artifactId

Android上发送带附件的邮件

准备工作-下载最新版本的JMail https://java.net/projects/javamail/pages/Home#Download_JavaMail_1.5.2_Release http://www.oracle.com/technetwork/java/javase/downloads/index-135046.html 在android上发送邮件方式: 第一种:借助GMail APP客户端,缺点是必须使用GMail帐号,有点是比较方便 不需要写很多代码,但是不是很灵活. 第二种

(转)用javamail发送带附件的邮件

本文转载自:http://redleaf.iteye.com/blog/78217 mail.java 代码 package mail; import java.util.* ; import java.io.* ; import javax.mail.* ; import javax.mail.internet.* ; import javax.activation.* ; public class Mail { //定义发件人.收件人.SMTP服务器.用户名.密码.主题.内容等 privat

自动化测试发送带附件的邮件

自动化测试发送带附件的邮件 标签(空格分隔): 带附件邮件 在我们的自动化测试中,有时候会发送报告,有时候会发送带附件的报告,具体带附件的报告怎么操作呢? 具体的步骤如下述所示:如下是QQ邮箱为例 import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart # 用于传送附件 smtpserver = 'smtp.exmail.qq.com' user = '*

C#发送带附件的邮件的代码

如下的代码是关于C#发送带附件的邮件的代码. MailMessage m = new MailMessage();m.Subject = "File attachment!";m.Body = "See the attached file.";m.Attachments.Add(new Attachment(@"C:test.txt"));SmtpClient client = new SmtpClient("smtp.w3mentor

Apache Mail 发送带附件的邮件

MultiPartEmail email = new MultiPartEmail(); email.setDebug(true); email.setHostName("smtp.sina.com"); email.setAuthentication("发送邮件帐号", "邮箱登录密码"); email.setCharset("UTF-8"); try { email.setFrom("发送邮件帐号",

Python发送带附件的SMTP邮件

利用python的email模块可以很方便的发送邮件,你甚至可以在邮件中附上附件!前提是你的邮箱开启了SMTP服务(一般都开启了,如果没有开启,可以到你的邮箱中进行设置),你可以把收件人和发件人都写成一个邮箱来进行测试,这样就是自己给自己发邮件. #coding: utf-8 import smtplib from email.mime.multipart import MIMEMultipart#python2.4及之前版本该模块不是这样调用的,而是email.MIMEMultipart.MI