Flask下的HTTP请求封装
from threading import Thread
from flask import current_app, render_template, app
from app import mail
from flask_mail import Message
def send_async_email(msg, app):
with app.app_context(): # 手动地推入栈中
try:
mail.send(msg)
except Exception as e:
pass
# 在虚拟环境中安装flask-mail
# to 代表发送给谁,subject代表发送的标题,template代表文章内容
def send_email(to, subject, template, **kwargs):
# msg = Message('测试邮件', sender='[email protected]', body='Test',
# recipients=['user.qq.com'])
# 测试邮件->标题,sender是MAIL_EMAIL是配置项,body是正文的内容,
# recipients表示接受方的邮箱
msg = Message(['琴书'] + ' ' + subject,
sender=current_app.config['MAIL_USERNAME'],
recipients=[to])
msg.html = render_template(template, **kwargs) # 渲染模板
# 获取到真实的flask的真实对象,避免线程调用的时候出现错误
app = current_app._get_current_object()
thr = Thread(target=send_async_email, args=[app, msg]) # 线程定义
# 调用线程,把发送邮件的动作留到后来进行,加快速度
thr.start()# 线程启动
# mail.send(msg) # 用第三方插件下的send方法来发送电子邮件,同步的send