使用 Python 標準庫 smtplib 與 email 套件發送郵件,支援 Gmail SMTP (SSL/TLS)、純文字/HTML 內容、多附件、抄送/密件抄送、錯誤處理。
smtp.gmail.com465 (SMTP over SSL)587 (STARTTLS)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('發送成功')
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)
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() |
pip install yagmail
import yagmail
yag = yagmail.SMTP('your@gmail.com', 'app_password')
yag.send('to@example.com', '主題', ['內容', 'attachment.pdf'])