因業務需求需要寄送大檔案,但是可能接收端的mail server 不允許夾帶大檔案之附件,故需要將檔案進行拆分壓縮,此時需要一個一個寄信就變成一件非常麻煩的事情,因此有了以下的程式碼!!

 

本案例是使用gmail的mail 服務,所以程式會透過 gmail 寄信。

 

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase 
from email import encoders
from importlib.resources import path 
from os import listdir,getcwd
from os.path import isfile, join, basename
import sys
import threading

import smtplib

def getAttachments(cwd):
    # cwd = join(getcwd(),"files")
    attachFiles = [join(cwd, f) for f in listdir(cwd) if isfile(join(cwd, f))]
    return attachFiles

def addAttchment(content,file):
    with open(file, 'rb') as fp:
        add_file = MIMEBase('application', "octet-stream")
        add_file.set_payload(fp.read())
    encoders.encode_base64(add_file)
    add_file.add_header('Content-Disposition', 'attachment', filename= basename(file))
    content.attach(add_file)

def getMailInfo(title):
    content = MIMEMultipart()  #建立MIMEMultipart物件
    content["subject"] = title  #郵件標題
    content["from"] = "tygr@gmail.example.com"  #寄件者
    content["to"] = "target@example.com" 
    content.attach(MIMEText("send mail by python script."))  #郵件內容

    return content

def send(content):
    with smtplib.SMTP(host="smtp.gmail.com", port="587") as smtp:  # 設定SMTP伺服器
        try:
            smtp.ehlo()  # 驗證 SMTP伺服器
            smtp.starttls()  # 建立加密傳輸
            smtp.login("tygr@gamil.com", "accountToken")  # 登入寄件者gmail
            smtp.send_message(content)  # 寄送郵件
        except Exception as e:
            print("Error message: ", e)


def sendMailPackage(idx, attachment):
    print("attachments file path = ", attachment)
    title = 'Realse ' + str(idx)
    content = getMailInfo(title)
    addAttchment(content=content,file=attachment)
    send(content=content)
    print("finish idx = " + str(idx))

def sendMail(cwd):
    print ("[info] = ",cwd)
    idx = 1
    ts = []
    for attachment in getAttachments(cwd):
        t = threading.Thread(target = sendMailPackage, args=(idx,attachment))
        t.start()
        idx += 1
        ts.append(t)
    
    for t in ts:
        t.join()

def main():
    if len(sys.argv) <= 1:
        cwd = join(getcwd(),"files")
        sendMail(cwd=cwd)
    else:
        sendMail(cwd = sys.argv[1])
    print("done.")
main()

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Lung-Yu,Tsai 的頭像
    Lung-Yu,Tsai

    Lung-Yu,Tsai 的部落格

    Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣()