萬盛學電腦網

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

Python smtplib 發送郵件完整指南:Gmail SMTP、SSL/TLS、附件與 HTML 郵件

使用 Python 標準庫 smtplib 與 email 套件發送郵件,支援 Gmail SMTP (SSL/TLS)、純文字/HTML 內容、多附件、抄送/密件抄送、錯誤處理。

Gmail 專用設定 (需啟用「應用程式密碼」)

  • SMTP 伺服器:smtp.gmail.com
  • SSL 埠口:465 (SMTP over SSL)
  • TLS 埠口:587 (STARTTLS)
  • 帳號:完整 Gmail 信箱
  • 密碼:應用程式密碼 (非登入密碼,需在 Google 帳號安全性設定生成)

基礎版:純文字郵件 (STARTTLS, 埠口 587)

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

# 設定
SMTP_HOST = 'smtp.gmail.com'
SMTP_PORT = 587
USERNAME = 'your@gmail.com'
PASSWORD = 'your_app_password'
FROM_ADDR = 'your@gmail.com'
TO_ADDR = 'recipient@example.com'

# 建立郵件
msg = MIMEMultipart()
msg['From'] = FROM_ADDR
msg['To'] = TO_ADDR
msg['Subject'] = 'Python 發送測試'
msg.attach(MIMEText('這是純文字內容', 'plain', 'utf-8'))

# 發送
with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
    server.ehlo()
    server.starttls()  # 升級加密
    server.ehlo()
    server.login(USERNAME, PASSWORD)
    server.send_message(msg)
    print('發送成功')

進階版:HTML 內容 + 附件

from email.mime.base import MIMEBase
from email import encoders
import os

msg = MIMEMultipart()
msg['From'] = FROM_ADDR
msg['To'] = TO_ADDR
msg['Cc'] = 'cc@example.com'
msg['Subject'] = 'HTML + 附件測試'

# HTML 內容
html = """

Python 郵件測試

支援 粗體, 連結, 圖片:

""" msg.attach(MIMEText(html, 'html', 'utf-8')) # 內嵌圖片 (CID) with open('logo.png', 'rb') as f: img = MIMEBase('image', 'png') img.set_payload(f.read()) encoders.encode_base64(img) img.add_header('Content-ID', '') img.add_header('Content-Disposition', 'inline', filename='logo.png') msg.attach(img) # 一般附件 for filepath in ['report.pdf', 'data.xlsx']: with open(filepath, 'rb') as f: part = MIMEBase('application', 'octet-stream') part.set_payload(f.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filepath)) msg.attach(part) # 發送 (含 Cc) recipients = [TO_ADDR] + (msg['Cc'].split(',') if msg['Cc'] else []) with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server: server.starttls() server.login(USERNAME, PASSWORD) server.send_message(msg, from_addr=FROM_ADDR, to_addrs=recipients)

SSL 直連版 (埠口 465)

with smtplib.SMTP_SSL(SMTP_HOST, 465) as server:
    server.login(USERNAME, PASSWORD)
    server.send_message(msg)

批量發送與速率控制

import time

recipients = ['a@x.com', 'b@x.com', 'c@x.com']
for to in recipients:
    msg['To'] = to
    with smtplib.SMTP(SMTP_HOST, SMTP_PORT) as server:
        server.starttls()
        server.login(USERNAME, PASSWORD)
        server.send_message(msg)
    time.sleep(1)  # 避免觸發反垃圾郵件限制

常見錯誤與解決

錯誤原因解決
535 Authentication failed密碼錯誤/未啟用應用程式密碼生成應用程式密碼、確認雙因子驗證
530 Must issue STARTTLS first未加密即嘗試登入先呼叫 starttls() 或用 SMTP_SSL
Connection timeout防火牆/網路/埠口錯誤檢查 465/587 埠連通性、嘗試 telnet
UnicodeEncodeError郵件標頭含非 ASCII使用 Header 編碼:Header('中文主題', 'utf-8').encode()

現代替代:yagmail (更簡潔)

pip install yagmail
import yagmail
yag = yagmail.SMTP('your@gmail.com', 'app_password')
yag.send('to@example.com', '主題', ['內容', 'attachment.pdf'])
copyright © 萬盛學電腦網 all rights reserved