您好,登錄后才能下訂單哦!
這篇文章主要講解了Python如何實(shí)現(xiàn)Flask異步發(fā)送郵件,內(nèi)容清晰明了,對(duì)此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會(huì)有幫助。
第一步,修改工廠函數(shù),配置郵件參數(shù)
from flask import Flask from config import Config from flask_sqlalchemy import SQLAlchemy from flask_mail import Mail db = SQLAlchemy() mail = Mail() def create_app(): app = Flask(__name__) app.config.from_object(Config) db.init_app(app) mail.init_app(app) from .controller import controller app.register_blueprint(controller) return app
第二步,新建一個(gè)線程來(lái)發(fā)送郵件
from flask import current_app, render_template from flask_mail import Message from threading import Thread from main import mail def send_async_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template = 'index', **kwargs): app = current_app._get_current_object() msg = Message(subject, sender = app.config['MAIL_USERNAME'], recipients = [to]) msg.html = render_template('{}.html'.format(template), **kwargs) thr = Thread(target = send_async_email, args = [app, msg]) thr.start() return thr
從current_app的_get_current_object()方法拿到應(yīng)用程序上下文。特此記錄一下
看完上述內(nèi)容,是不是對(duì)Python如何實(shí)現(xiàn)Flask異步發(fā)送郵件有進(jìn)一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。