首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 發送 Email 三大法:SMTP 登入、sendmail 指令、本地 SMTP 服務完整範例

     編輯:更多程式設計知識

Python 發送郵件主要有三條路徑:SMTP 登入遠端郵件伺服器、Linux 呼叫 sendmail 指令、直連本地/遠端 SMTP 服務。本文提供三種方式的最小可執行程式碼,涵蓋純文字、HTML、附件擴充說明。

方式一:SMTP 登入(最通用,支援 126、Gmail、Outlook 等)

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 需開啟「低安全性應用程式存取」或使用應用程式密碼。

方式二:Linux 呼叫 sendmail 指令(無需 SMTP 伺服器帳密)

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,否則易進垃圾信箱。
  • 適合內網監控腳本、無外部 SMTP 權限環境。

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

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()
  • 本機需啟動 Postfix/Sendmail 並開放 25 port。
  • 遠端 SMTP 若為開放中繼 (Open Relay) 極危險,生產環境嚴禁。

進階擴充:HTML 郵件與附件

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)

掌握三種路徑,即可因地制宜在任何環境可靠發送郵件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved