Python 發送郵件主要有三條路徑:SMTP 登入遠端郵件伺服器、Linux 呼叫 sendmail 指令、直連本地/遠端 SMTP 服務。本文提供三種方式的最小可執行程式碼,涵蓋純文字、HTML、附件擴充說明。
import smtplib
from email.mime.text import MIMEText
SMTP_SERVER = 'smtp.126.com'
SENDER = 'liuzhizhi123@126.com'
PASSWORD = 'xxxx' # 授權碼而非登入密碼
RECEIVER = 'destination@example.com'
msg = MIMEText('I send a message by Python. 你好', 'plain', 'utf-8')
msg['Subject'] = 'Test Email by Python'
msg['From'] = SENDER
msg['To'] = RECEIVER
server = smtplib.SMTP(SMTP_SERVER, 25)
server.login(SENDER, PASSWORD)
server.sendmail(SENDER, [RECEIVER], msg.as_string())
server.quit()
print('send email success')
關鍵點:啟用 SMTP 服務並取得授權碼;Gmail 需開啟「低安全性應用程式存取」或使用應用程式密碼。
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
def mail_send(sender, receiver):
msg = MIMEText('郵件內容')
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = '標題'
p = Popen(['/usr/sbin/sendmail', '-t'], stdin=PIPE)
p.communicate(msg.as_string())
/usr/sbin/sendmail 存在且 MTA (Postfix/Exim) 已正確設定主機名、反向解析、SPF/DKIM,否則易進垃圾信箱。import smtplib
from email.mime.text import MIMEText
def mail_send(sender, receiver):
msg = MIMEText('內容')
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = '標題'
s = smtplib.SMTP('localhost') # 或遠端 IP
s.sendmail(sender, [receiver], msg.as_string())
s.quit()
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
msg = MIMEMultipart()
msg.attach(MIMEText('HTML 內容
', 'html', 'utf-8'))
att = MIMEApplication(open('report.pdf', 'rb').read())
att.add_header('Content-Disposition', 'attachment', filename='report.pdf')
msg.attach(att)
| 場景 | 推薦方式 |
|---|---|
| 一般應用、雲端部署 | 方式一 (SMTP 登入) |
| Linux 內網監控、無帳密 | 方式二 (sendmail) |
| 自建郵件閘道、高吞吐 | 方式三 (直連 SMTP) |
掌握三種路徑,即可因地制宜在任何環境可靠發送郵件。