Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Python 使用 smtplib 發送含附件郵件

在系統監控、自動化運維與網站通知等情境中,寄送電子郵件是常見需求。Python 可透過 smtplib 與 email 模組完成含附件的郵件發送。

常用 SMTP 方法

  • SMTP():建立 SMTP 連線。
  • connect():連線到指定主機與埠。
  • login():登入 SMTP 伺服器。
  • sendmail():寄送郵件。
  • quit():結束連線。

附件處理

郵件內容可由 MIMEMultipart、MIMEText 與 MIMEImage 等物件組合。附件可透過猜測檔案類型後附加到郵件中。

import os, smtplib, mimetypes
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage

MAIL_HOST = "smtp.example.com"
MAIL_USER = "username"
MAIL_PASS = "password"
MAIL_LIST = ["user@example.com"]
MAIL_FROM = "username@example.com"

def send_mail(subject, content, filename=None):
    message = MIMEMultipart()
    message.attach(MIMEText(content))
    message["Subject"] = subject
    message["From"] = MAIL_FROM
    message["To"] = ";".join(MAIL_LIST)

    if filename and os.path.exists(filename):
        ctype, encoding = mimetypes.guess_type(filename)
        if ctype is None or encoding is not None:
            ctype = "application/octet-stream"
        maintype, subtype = ctype.split("/", 1)
        with open(filename, "rb") as f:
            attachment = MIMEImage(f.read(), _subtype=subtype)
        attachment.add_header("Content-Disposition",
                              "attachment", filename=filename)
        message.attach(attachment)

    smtp = smtplib.SMTP()
    smtp.connect(MAIL_HOST)
    smtp.login(MAIL_USER, MAIL_PASS)
    smtp.sendmail(MAIL_FROM, MAIL_LIST, message.as_string())
    smtp.quit()
Copyright © Linux教程網 All Rights Reserved