标签:安装 ret current code word nts with span serve
安装
pip install Flask-Mail
Config.py
class Config: SQLALCHEMY_TRACK_MODIFICATIONS = False SQLALCHEMY_ECHO = False MAIL_SERVER = ‘smtp.126.com‘ MAIL_USERNAME = ‘xxx@126.com‘ MAIL_PASSWORD = ‘xxx‘
新建py文件send_mail.py:然后新建一个类BaseMail 继承Flask Mail的 Mail
from flask_mail import Mail from flask import current_app from threading import Thread class BaseMail(Mail): def async_send_mail(self, message): # current_app._get_current_object() 返回当前app thread = Thread(target=self._send_async_mail, args=[current_app._get_current_object(), message]) thread.start() def _send_async_mail(self, app, message): with app.app_context(): self.send(message)
app.py:这时初始化Mail的时候直接用继承后的BaseMail
from tools.send_email import BaseMail app = Flask(__name__) mail = BaseMail(app) def create_app(config_name=‘test‘): app.config.from_object(app_config[config_name]) mail.init_app(app) return app
view中使用:直接import app.py中的mail进行发送,使用mail.async_send_mail方式即可异步发送
from init import mail from flask_mail import Message # send email msg = Message(‘用户创建成功通知‘, sender=‘xxxxx@126.com‘, recipients=[‘abc@163.com‘,‘abc@126.com‘])
msg.html = ‘<h3>尊敬的<span style="color: red">%s</span>帅哥/美女:</h3><div>您的账号已经创建成功,请妥善保管您的密码,祝你使用愉快~</div>‘ % username mail.async_send_mail(msg)
标签:安装 ret current code word nts with span serve
原文地址:https://www.cnblogs.com/gongnanxiong/p/11743144.html