python 壓縮檔案並進行郵件傳送(附件格式為zip)

專注的阿熊發表於2021-08-24

# coding=gbk

import zipfile

import os

import mimetypes

import smtplib   # 傳送郵件模組

from email import encoders

from email.mime.multipart import MIMEMultipart    # 使用 MIMEMultipart 來標示這個郵件是多個部分組成的

from email.mime.base import MIMEBase

from email.mime.text import MIMEText   # 定義郵件內容

import  datetime

from email.utils import formataddr

def zipDir(dirpath, outFullName):

     zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)

     for path, dirnames, filenames in os.walk(dirpath):

         # 去掉目標跟路徑,只對目標資料夾下邊的檔案及資料夾進行壓縮

         fpath = path.replace(dirpath, '')

         for filename in filenames:

             zip.write(os.path.join(path, filename), os.path.join(fpath, filename))

     zip.close()

     print(' 壓縮成功 ')

def send_email():

     filepath = "D:\Email\ 介面測試報告 .zip"     # 要傳送的壓縮檔案路徑

     smtp_server = "smtp.163.com"      # 傳送郵箱伺服器

     username = "abc@163.com"      # 用於傳送郵箱的使用者賬號

     password = "xxxxx"      # 密碼 ( 即授權碼 )

     sender = 'abc@163.com'  # 傳送者的郵箱

     receivers = ['123@qq.com', '456@qq.com', '789@qq.com']   # 接收者的郵箱

     EMAIL_FROM_NAME = ' 測試平臺 '   # 自定義發件人名稱

     time = datetime.datetime.today().strftime("%m-%d %H %M")

     msg = MIMEMultipart()

     # 郵件正文

     msg.attach(MIMEText("hi all \r\njmeter 介面測試報告結果請檢視附件 ",'plain','utf-8'))   # 文字內容換行 \r\n

     msg['From'] = formataddr(pair=(EMAIL_FROM_NAME, sender))     # 自定義發件人的名稱

     # msg['To'] = receivers[0]  # 外匯跟單gendan5.com 傳送給 receivers 裡的第一個使用者

     msg['To'] = ";".join(receivers)  # 傳送給多個好友

     subject = "{}--jmeter 介面測試報告 ".format(time)

     msg['Subject'] = subject

     data = open(filepath, 'rb')

     ctype, encoding = mimetypes.guess_type(filepath)

     if ctype is None or encoding is not None:

         ctype = 'application/octet-stream'

     maintype, subtype = ctype.split('/', 1)

     file_msg = MIMEBase(maintype, subtype)

     file_msg.set_payload(data.read())

     data.close()

     encoders.encode_base64(file_msg)  # 把附件編碼

     file_msg.add_header('Content-Disposition', 'attachment', filename=" 測試報告 .zip")  # 修改郵件頭

     msg.attach(file_msg)

     try:

         server = smtplib.SMTP(smtp_server)

         server.login(username,password)

         server.sendmail(sender,receivers,msg.as_string())

         server.quit()

         print(" 傳送成功 ")

     except Exception as err:

         print(" 傳送失敗 ")

         print(err)

if __name__ =='__main__':

     # dirpath 為要壓縮的資料夾路徑, outFullName 為壓縮完後要存放的路徑

     dirpath = r'D:\ 介面測試報告 \ 介面測試報告 '

     outFullName = r'D:\Email\ 介面測試報告 .zip'

     zipDir(dirpath, outFullName)

     send_email()


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2788562/,如需轉載,請註明出處,否則將追究法律責任。

相關文章