【flask-Email】郵件發送

使用依賴:flask

flask_mailapp

安裝方式: 異步

pip3 install flask-mail

 代碼示例: async

from flask import Flask from flask_mail import Mail, Message app = Flask(__name__)
#經過app.config對象的update()方法來加載配置 app.config.update( MAIL_SERVER
="smtp.xxx.com", MAIL_USE_SSL=True, MAIL_PORT=465, MAIL_USERNAME='wangju@xxx.com', MAIL_PASSWORD="受權碼", MAIL_DEFAULT_SENDER=('wangju', 'wangju@xxx.com') #默認發件人 發件人郵箱 ) mail = Mail(app) subject='腳本測試用例維護通知' #郵件主題 recipients='wxx@xxx.com' #收件人 body='測試郵件' #郵件內容 #發送郵件 def send_email(subject,to,body): message = Message(subject,recipients=[to],body=body) mail.send(message) @app.route('/') def subscribe(): send_email(subject,'收件人郵件',body) return '發送郵件成功,請查收' if __name__ == '__main__': app.run(debug=True)

遇到的問題1:ide

運行demo.py時報錯:函數

RuntimeError: Working outside of application context

查詢了一番,只知道這個錯的意思是沒有激活上下文,可是不清楚,沒有激活上下文又表明什麼意思。測試

最後才發現,原來就是我在demo.py中spa

 

加了視圖函數subscribe(),並在其中調用 send_email,就能夠正常發送郵件了。線程

 

參考文檔:debug

Flask拋出RuntimeError: Working outside of application context.錯誤

遇到的問題2:

在視圖函數中調用 send_email()函數,致使響應時間超過20秒

這是由於 程序正在發送電子郵件,發信的操做阻斷了請求-響應循環,直到發信的send_mail()函數調用結束後,視圖函數纔會返回響應。

爲了不這個延遲,能夠將發信函數放入後臺線程異步執行。

示例代碼:

 

from threading import Thread #異步發送電子郵件
def _send_async_mail(app,message): with app.app_context(): mail.send(message) def send_email(subject,to,body): message = Message(subject,recipients=[to],body=body) thr=Thread(target=_send_async_mail,args=[app,message]) thr.start() return thr

 

由於Flask-Mail的send()方法內部調用邏輯中使用了current_app變量,而這個變量只在激活的程序上下文中才存在,這裏在後臺線程調用

發信函數,可是後臺線程並無程序上下文存在。爲了正常實現發信功能,咱們傳入程序實例app做爲參數,並調用app.app_context()手動激活程序上下文 。

再次調用接口發現,響應時間從原來的20s變爲了0.7s

相關文章
相關標籤/搜索