Web 應用離不開郵件通知:註冊驗證、密碼重設、新追蹤者提醒等。Flask-Mail 封裝 smtplib,提供優雅的異步發送、模板渲染、附件支援。本文從安裝到建立可復用郵件框架,一步步打造生產級郵件系統。
# Linux/macOS
pip install flask-mail
# Windows(需預編譯依賴)
pip install --no-deps lamson chardet flask-mail
config.py# Gmail 範例(需開啟「低安全性應用」或使用應用程式密碼)
MAIL_SERVER = 'smtp.gmail.com'
MAIL_PORT = 465
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_USERNAME = 'your@gmail.com'
MAIL_PASSWORD = 'your-app-password'
# 管理員清單(用於錯誤通知等)
ADMINS = ['admin@example.com']
app/__init__.pyfrom flask import Flask
from flask_mail import Mail
app = Flask(__name__)
app.config.from_object('config')
mail = Mail(app)
from app import views, models
app/emails.pyfrom flask import render_template, current_app
from flask_mail import Message
from app import mail
def send_email(subject, sender, recipients, text_body, html_body):
"""通用發送函式:支援純文字 + HTML 多部分郵件"""
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
msg.html = html_body
mail.send(msg)
def follower_notification(followed, follower):
"""新追蹤者通知:使用模板分離內容與邏輯"""
send_email(
subject=f"[Microblog] {follower.nickname} 開始追蹤你!",
sender=current_app.config['ADMINS'][0],
recipients=[followed.email],
text_body=render_template('emails/follower.txt', user=followed, follower=follower),
html_body=render_template('emails/follower.html', user=followed, follower=follower)
)
templates/emails/follower.txt親愛的 {{ user.nickname }},
{{ follower.nickname }} 現在正在追蹤你。
點擊連結查看個人頁面:
{{ url_for('user', nickname=follower.nickname, _external=True) }
祝愉快,
Microblog 團隊
templates/emails/follower.html<p>親愛的 {{ user.nickname }},</p>
<p><a href="{{ url_for('user', nickname=follower.nickname, _external=True) }}">
{{ follower.nickname }}
</a> 現在正在追蹤你。</p>
<p>祝愉快,<br>Microblog 團隊</p>
from threading import Thread
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(subject, sender, recipients, text_body, html_body):
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
msg.html = html_body
Thread(target=send_async_email, args=(current_app._get_current_object(), msg)).start()
生產環境建議搭配 Celery + Redis/RabbitMQ 實現真正的分散式任務佇列。
>> from flask_mail import Message
>>> from app import mail, app
>>> from config import ADMINS
>>> with app.app_context():
... msg = Message('Test', sender=ADMINS[0], recipients=ADMINS)
... msg.body = 'Plain text'
... msg.html = 'HTML body'
... mail.send(msg)
MAIL_USE_SSL=True 時 port 通常為 465;MAIL_USE_TLS=True 時為 587。MAIL_SUPPRESS_SEND = True 僅記錄不發送。Flask-Mail + Jinja2 模板 + 非同步發送 = 乾淨、可維護、可擴展的郵件系統。將郵件內容抽離為模板,讓設計師能獨立調整版面,工程師專注業務邏輯,雙贏。