1. 程式人生 > >python 發送帶有附件的郵件

python 發送帶有附件的郵件

容錯 圖文 打包 odi mime ror not htm 排序

在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 MIMEMultipart
from 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

python 發送帶有附件的郵件