萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

Python smtplib 郵件發送完整指南:從基礎 SMTP 到 MIME 多媒體附件實戰

前言

`smtplib` 是 Python 標準庫中的 SMTP 客戶端實現,配合 `email` 套件可構建功能完整的郵件發送系統。本文從最簡單的純文字郵件進階到 HTML 內容、嵌入圖片、多附件、SSL/TLS 加密連線。

環境準備


# 無需額外安裝,標準庫即含
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication

基礎:純文字郵件


def send_plain_text():
    smtp = smtplib.SMTP('smtp.example.com', 587)
    smtp.starttls() # 啟用 TLS 加密
    smtp.login('user@example.com', 'password')
    
    msg = MIMEText('這是純文字內容', 'plain', 'utf-8')
    msg['From'] = 'Sender '
    msg['To'] = 'Recipient '
    msg['Subject'] = '測試郵件'
    
    smtp.send_message(msg)
    smtp.quit()

進階:HTML 郵件 + 內嵌圖片


def send_html_with_image():
    msg = MIMEMultipart('related') # related: HTML 引用內嵌資源
    msg['From'] = 'Sender '
    msg['To'] = 'Recipient '
    msg['Subject'] = 'HTML 郵件測試'
    
    # HTML 內容(cid: 引用內嵌圖片)
    html = '''
    
      

歡迎使用我們的服務

Logo

詳細資訊請見 官網

''' msg.attach(MIMEText(html, 'html', 'utf-8')) # 內嵌圖片 with open('logo.png', 'rb') as f: img = MIMEImage(f.read()) img.add_header('Content-ID', '') # 對應 cid:logo_image msg.attach(img) with smtplib.SMTP_SSL('smtp.example.com', 465) as smtp: smtp.login('user', 'pass') smtp.send_message(msg)

附件處理:通用附件類


def attach_file(msg, filepath, filename=None):
    with open(filepath, 'rb') as f:
        part = MIMEApplication(f.read(), Name=filename or os.path.basename(filepath))
    part['Content-Disposition'] = f'attachment; filename="{filename or os.path.basename(filepath)}"'
    msg.attach(part)

# 使用
msg = MIMEMultipart()
attach_file(msg, 'report.pdf', '月報.pdf')
attach_file(msg, 'data.xlsx')

完整發送函數(支援 TLS/SSL、多收件人、抄送、附件、HTML)


import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

def send_email(
    host, port, user, password,
    from_addr, to_addrs, subject,
    text_body=None, html_body=None,
    attachments=None, # [{path, filename, mimetype}]
    cc=None, bcc=None,
    use_ssl=False, use_tls=True
):
    msg = MIMEMultipart('mixed')
    msg['From'] = from_addr
    msg['To'] = ', '.join(to_addrs) if isinstance(to_addrs, list) else to_addrs
    if cc: msg['Cc'] = ', '.join(cc)
    msg['Subject'] = subject
    
    # 替代部件:text/plain + text/html
    alternative = MIMEMultipart('alternative')
    if text_body:
        alternative.attach(MIMEText(text_body, 'plain', 'utf-8'))
    if html_body:
        alternative.attach(MIMEText(html_body, 'html', 'utf-8'))
    msg.attach(alternative)
    
    # 附件
    for att in (attachments or []):
        with open(att['path'], 'rb') as f:
            part = MIMEBase(*att.get('mimetype', 'application/octet-stream').split('/'))
            part.set_payload(f.read())
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment', filename=att.get('filename', os.path.basename(att['path'])))
        msg.attach(part)
    
    # 發送
    all_recipients = list(to_addrs) + (cc or []) + (bcc or [])
    ctx = None
    if use_ssl:
        smtp = smtplib.SMTP_SSL(host, port)
    else:
        smtp = smtplib.SMTP(host, port)
        if use_tls:
            smtp.starttls()
    
    try:
        smtp.login(user, password)
        smtp.sendmail(from_addr, all_recipients, msg.as_string())
    finally:
        smtp.quit()

# 使用範例
send_email(
    host='smtp.gmail.com', port=587,
    user='me@gmail.com', password='app_password',
    from_addr='me@gmail.com',
    to_addrs=['you@example.com'],
    cc=['boss@example.com'],
    subject='報表',
    text_body='請見附件',
    html_body='

請見附件

', attachments=[{'path': 'report.pdf', 'filename': 'Q4報表.pdf'}] )

常見問題排解

錯誤原因與解決
SMTPAuthenticationError帳號/密碼錯誤、需開啟「低安全性應用」或使用應用程式密碼(Gmail/Outlook)
SMTPConnectError / Timeout埠號錯誤(25/465/587)、防火牆攔截、網路不通
SMTPRecipientsRefused收件人地址格式錯誤、被拒收
郵件進垃圾桶缺少 SPF/DKIM/DMARC 設定、內容觸發反垃圾規則、IP 信譽差
中文附件檔名亂碼使用 `email.header.Header` 編碼或 `MIMEBase` 正確設定 filename 參數

生產環境最佳實踐

  1. 使用專用交易郵件服務(SendGrid, Mailgun, Amazon SES, Postmark)而非自建 SMTP
  2. 實作重試機制(指數退避)與發送隊列(Celery/RQ + Redis)
  3. 記錄發送日誌(Message-ID、狀態、錯誤)供追蹤
  4. 模板引擎分離內容(Jinja2)
  5. 定期驗證郵件送達率、退信率、開信率

總結

Python `smtplib` + `email` 套件提供完整、標準化的郵件發送能力。掌握 MIME 多部分結構(alternative/related/mixed)、編碼處理、TLS/SSL 連線模式,即可構建企業級郵件發送模組。生產環境強烈建議對接專業郵件服務商 API,獲得更高送達率、詳細分析與彈性擴展。

copyright © 萬盛學電腦網 all rights reserved