flask-mail使用

flask-mail使用

  • flask-mail安装
  • email配置
  • 封装email发送方法

flask-mail安装

pipenv install flask-mail

email配置

from flask_mail import Mail

mail = Mail()
mail.init_app(app)

secure.py配置文件添加邮件相关配置

# Email 配置
MAIL_SERVER = 'smtp.qq.com'
MAIL_PORT = 465
MAIL_USE_SSL = True
MAIL_USE_TSL = False
MAIL_USERNAME = '[email protected]'
MAIL_PASSWORD = 'xxxx'

封装email发送方法

from app import mail


def send_async_email(app, msg):
    with app.app_context():
        try:
            mail.send(msg)
        except Exception as e:
            pass

由于发送邮件耗时,再封装异步调用

def send_email(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    msg = Message('[E-car]' + ' ' + subject,
                  sender=app.config['MAIL_USERNAME'], recipients=[to])
    # msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr

你可能感兴趣的:(Flask,flask-mail)