Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Flask-Mail 擴充套件實用指南:同步、異步寄信與上下文陷阱

幾乎每個 Web 應用都會遇到寄信需求:註冊驗證、密碼重設、通知提醒。Flask 生態中,Flask-Mail 是最省事的選擇。

安裝與使用四步

pip install flask-mail
  1. 設定寄信參數:伺服器位址、埠、是否加密、帳號密碼等。
  2. 初始化 Flask-Mail 擴充。
  3. 建立 Message 實例,填入收件者、主旨與內容。
  4. 呼叫 Mail 實例的 send() 送出。

常用設定參數

  • MAIL_SERVER:郵件伺服器位址或 IP,預設 localhost。
  • MAIL_PORT:埠號,預設 25。
  • MAIL_USE_TLS:是否啟用 TLS 加密(預設 False)。
  • MAIL_USE_SSL:是否啟用 SSL 加密(預設 False)。
  • MAIL_USERNAME / MAIL_PASSWORD:寄信帳號與密碼。

實務上 465 埠搭配 SSL、587 埠搭配 TLS 最常見;Gmail、163 等服務商通常還要求使用「應用程式專用密碼」而非登入密碼。

初始化

from flask_mail import Mail
mail = Mail(app)

與多數 Flask 擴充一致,把 app 實例傳進去即可完成綁定。

寄一封信

from flask_mail import Message

def send_email():
    msg = Message("郵件主旨",
                  sender="localhost",
                  recipients=["445188382@qq.com"])
    msg.body = "純文字內容"
    msg.html = "<h1>HTML 內容</h1> 其餘文字"
    mail.send(msg)

同時提供 body 與 html 時,客戶端會依能力挑選顯示;只提供 html 的郵件在純文字環境下容易直接被判定為垃圾郵件,因此建議兩者都給。

同步寄信的問題與異化解法

直接呼叫 mail.send() 是同步的:使用者按下送出後,頁面會卡住數秒直到 SMTP 交談結束。解法是丟到背景執行緒:

from threading import Thread

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_email():
    msg = Message("郵件主旨",
                  sender="localhost",
                  recipients=["445188382@qq.com"])
    msg.body = "純文字內容"
    msg.html = "<b>HTML</b> 內容"

    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return "OK"

為什麼一定要 app_context()

許多 Flask 擴充都假定自己運行在活動的應用與請求上下文中。Flask-Mail 的 send() 內部使用了 current_app,因此在子執行緒中必須人為建立應用上下文,否則會抛出「Working outside of application context」。原文的說明是:

Many Flask extensions operate under the assumption that there are active application and request contexts. Flask-Mail's send() function uses current_app, so it requires the application context to be active. But when the mail.send() function executes in a different thread, the application context needs to be created artificially using app.app_context().

完整可運行範例

from flask import Flask
from flask_mail import Mail, Message
from threading import Thread

app = Flask(__name__)
app.config['MAIL_SERVER'] = 'localhost'
app.config['MAIL_PORT'] = 25

mail = Mail(app)

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

@app.route("/mail")
def SendMail():
    msg = Message('test',
                  sender='zyfforlinux@163.com',
                  recipients=['445188383@qq.com'])
    msg.body = "text body"
    msg.html = "<b>HTML</b> body"

    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return "OK"

給新專案的建議

範例中的 flask.ext.mail 匯入路徑已於新版 Flask 淘汰,請直接寫 from flask_mail import Mail, Message。若寄信量較大,用執行緒只是權宜之計,正式環境建議改用 Celery、RQ 或任何背景任務佇列,並搭配寄信失敗的重試與記錄機制,避免信件在重啟時靜默消失。

Copyright © Linux教程網 All Rights Reserved