使用flask mail發送mail

參考: http://pythonhosted.org/Flask-Mail/
使用pip安裝插件:
pip install Flask-Mail
在flask程序的config.cfg中加入以下內容,根據你郵件客戶端的配置或者郵箱服務商提供的幫助文檔即可:
MAIL_SERVER = ‘mail.example.cn’
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USERNAME = ‘[email protected]
MAIL_DEFAULT_SENDER = ‘[email protected]
MAIL_PASSWORD = ‘mypwd’
mail.py代碼如下:

from threading import Thread
from flask import current_app, render_template
from flask_mail import Mail, Message
g_mail = None
def send_async_email(app, msg):
    global g_mail
    with app.app_context():
        g_mail.send(msg)
def send_email(to, subject, html):
    global g_mail
    app = current_app._get_current_object()
    g_mail = Mail(app)
    msg = Message(subject=subject, recipients=to, html=html)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr

在需要發送郵件的文件,使用下面代碼就可以異步發送郵件了

from mail import send_email
send_email(to, subject, html)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章