Flask-Mail - Sending email asynchronously, based on Flask-Cookiecutter

后端 未结 3 667
耶瑟儿~
耶瑟儿~ 2021-02-06 10:47

My flask project is based on Flask-Cookiecutter and I need to send emails asynchronously.

Function for sending email was configured by Miguel’s Tutorial and sending sync

3条回答
  •  孤街浪徒
    2021-02-06 10:58

    Move email send function to a background thread:

    from threading import Thread
    
    def send_async_email(app,msg):
           with current_app.app_context():
                   mail.send(msg)
    
    def send_email(to, subject, template, **kwargs):
           msg = Message(subject, recipients=[to])
           msg.html = render_template('emails/' + template, **kwargs)
           thr = Thread(target=send_async_email,args=[app,msg])
           thr.start()
           return thr
    

提交回复
热议问题