在本文中將使用 smtplib 、email.mime 來達成用 Gmail 寄發包含多個附檔的信件。
基本上都會遇到 “允許低安全性應用程式存取您的帳戶" 的問題,所以在開始前,請先去啟用寄信帳戶的“允許低安全性應用程式"設定,這樣才會通過登入驗證。
接下來直接用程式碼說明:
import smtplib from email.mime.multipart import MIMEMultipart #email內容載體 from email.mime.text import MIMEText #用於製作文字內文 from email.mime.base import MIMEBase #用於承載附檔 from email import encoders #用於附檔編碼 #設定要使用的Gmail帳戶資訊 gmail_user = 'YOUR EMAIL' gmail_password = 'YOUR EMAIL password' #設定寄件資訊 from_address = gmail_user to_address = ['TARGET EMAIL'] Subject = "TEST:Python Gmail 寄信 with 附加多個檔案" contents = """ 信件內文 """ attachments = ['file1.txt','file2.txt'] #開始組合信件內容 mail = MIMEMultipart() mail['From'] = from_address mail['To'] = ', '.join(to_address) mail['Subject'] = Subject #將信件內文加到email中 mail.attach(MIMEText(contents)) #將附加檔案們加到email中 for file in attachments: 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=file) mail.attach(add_file) #設定smtp伺服器並寄發信件 smtpserver = smtplib.SMTP_SSL("smtp.gmail.com",465) smtpserver.ehlo() smtpserver.login(gmail_user, gmail_password) smtpserver.sendmail(from_address, to_address, mail.as_string()) smtpserver.quit()
上述程式碼只能用來附件純文字檔,如果要附件多媒體檔案,可以參考官方範例,但基本架構是不變的,只是要多做些設定。