Python 發送郵件有多種路徑。本文完整對比三種方案:登入郵件服務商 SMTP、Linux sendmail 指令、本地/遠端 SMTP 服務,提供可直接使用的程式碼模板,涵蓋單發、群發、抄送、HTML 郵件、附件等進階需求。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
SMTP_SERVER = 'smtp.126.com'
SENDER = 'liuzhizhi123@126.com'
PASSWORD = 'xxxx' # 授權碼而非登入密碼
RECIPIENT = 'target@example.com'
message = 'I send a message by Python. 你好'
msg = MIMEText(message, 'plain', 'utf-8')
msg['Subject'] = 'Test Email by Python'
msg['From'] = SENDER
msg['To'] = RECIPIENT
server = smtplib.SMTP(SMTP_SERVER, 25)
server.login(SENDER, PASSWORD)
server.sendmail(SENDER, [RECIPIENT], msg.as_string())
server.quit()
print('send email success')
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg['Subject'] = 'Report'
msg['From'] = SENDER
msg['To'] = ', '.join(['a@b.com', 'c@d.com'])
msg['Cc'] = 'cc@example.com'
# HTML 內容
html = """Report
Detail...
"""
msg.attach(MIMEText(html, 'html', 'utf-8'))
# 附件
with open('report.pdf', 'rb') as f:
part = MIMEApplication(f.read(), Name='report.pdf')
part['Content-Disposition'] = 'attachment; filename="report.pdf"'
msg.attach(part)
server.sendmail(SENDER, msg['To'].split(', ') + msg['Cc'].split(', '), msg.as_string())
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
def send_via_sendmail(sender, recipient, subject, body):
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject
p = Popen(['/usr/sbin/sendmail', '-t', '-oi'], stdin=PIPE)
p.communicate(msg.as_string())
return p.returncode == 0
前提:系統已配置 sendmail/postfix、/etc/hosts 主機名正確、防火牆放行 25 埠。
import smtplib
from email.mime.text import MIMEText
def send_via_local_smtp(sender, recipient, subject, body):
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = sender
msg['To'] = recipient
msg['Subject'] = subject
s = smtplib.SMTP('localhost') # 或遠端 IP
s.sendmail(sender, [recipient], msg.as_string())
s.quit()
前提:本地 postfix/sendmail 服務運行中(ps -ef | grep sendmail、telnet localhost 25 驗證)。
| 維度 | SMTP 登入 | sendmail 指令 | 本地 SMTP |
|---|---|---|---|
| 跨平台 | ✅ 是 | ❌ 僅 Unix | ✅ 是 |
| 需郵件服務商帳號 | ✅ 是 | ❌ 否 | ❌ 否 |
| 需本地 MTA 配置 | ❌ 否 | ✅ 是 | ✅ 是 |
| 發送可靠性 | 高(服務商負責佇列重試) | 中(依賴本地佇列) | 中(需自行配置重試) |
| 大量郵件適用 | ✅(配合專用服務) | ⚠️ 易被判垃圾郵件 | ⚠️ 需專業配置 |
| 附件/HTML 支援 | ✅ 完整 | ✅ 完整 | ✅ 完整 |
mailcatcher/ethereal.email