萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 發送 Email 三大方案完整對比:SMTP 登入、sendmail 指令、本地 SMTP 服務

Python 發送郵件有多種路徑。本文完整對比三種方案:登入郵件服務商 SMTP、Linux sendmail 指令、本地/遠端 SMTP 服務,提供可直接使用的程式碼模板,涵蓋單發、群發、抄送、HTML 郵件、附件等進階需求。

方案一:登入郵件服務商 SMTP(最通用)

#!/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')

進階:HTML 郵件與附件

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())

方案二:Linux sendmail 指令(無需 SMTP 伺服器)

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 埠。

方案三:本地/遠端 SMTP 服務(無需登入)

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 支援✅ 完整✅ 完整✅ 完整

生產環境核心建議

  1. 使用專業郵件服務:SendGrid、Mailgun、Amazon SES、Postmark,提供 API、佇列、退信處理、聲譽管理
  2. 非同步發送:Celery + Redis/RabbitMQ 佇列,避免阻塞主流程
  3. 模板引擎:Jinja2 渲染 HTML 郵件,分離內容與樣式
  4. 去識別化測試:測試環境攔截郵件或使用 mailcatcher/ethereal.email
  5. 合規:包含退訂連結、實體地址、遵守 CAN-SPAM/GDPR
copyright © 萬盛學電腦網 all rights reserved