`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()
def send_html_with_image():
msg = MIMEMultipart('related') # related: HTML 引用內嵌資源
msg['From'] = 'Sender '
msg['To'] = 'Recipient '
msg['Subject'] = 'HTML 郵件測試'
# HTML 內容(cid: 引用內嵌圖片)
html = '''
歡迎使用我們的服務
詳細資訊請見 官網
'''
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')
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 參數 |
Python `smtplib` + `email` 套件提供完整、標準化的郵件發送能力。掌握 MIME 多部分結構(alternative/related/mixed)、編碼處理、TLS/SSL 連線模式,即可構建企業級郵件發送模組。生產環境強烈建議對接專業郵件服務商 API,獲得更高送達率、詳細分析與彈性擴展。