参考: 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 = ‘example@niot.cn’
MAIL_DEFAULT_SENDER = ‘example@example.cn’
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)