使用 Python 的 smtplib 發送電子郵件附件可能具有挑戰性,尤其是對於初學者而言。為了提供更易於理解的解釋,我們探索了一種全面的方法。
考慮以下程式碼片段:
import smtplib from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import COMMASPACE, formatdate def send_mail(send_from, send_to, subject, text, files=None, server="127.0.0.1"): assert isinstance(send_to, list) msg = MIMEMultipart() msg['From'] = send_from msg['To'] = COMMASPACE.join(send_to) msg['Date'] = formatdate(localtime=True) msg['Subject'] = subject msg.attach(MIMEText(text)) for f in files or []: with open(f, "rb") as fil: part = MIMEApplication( fil.read(), Name=basename(f) ) # After the file is closed part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f) msg.attach(part) smtp = smtplib.SMTP(server) smtp.sendmail(send_from, send_to, msg.as_string()) smtp.close()
分解程式碼:
這種方法可以讓您清楚地了解發送電子郵件所涉及的必要步驟附件。
以上是如何使用Python的smtplib輕鬆發送電子郵件附件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!