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

后端 未结 3 665
耶瑟儿~
耶瑟儿~ 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:48

    Okay, i found solution for my question i posting it here for others developers:

    I create file: email.py with code:

    from threading import Thread
    from flask import current_app, render_template
    from flask_mail import Message
    from .extensions import mail
    from time import sleep    
    
    def send_async_email(app, msg):
        with app.app_context():
            # block only for testing parallel thread
            for i in range(10, -1, -1):
                sleep(2)
                print('time:', i)
            print('====> sending async')
            mail.send(msg)
    
    def send_email(to, subject, template, **kwargs):
        app = current_app._get_current_object()
        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
    

    my view.py:

    ...
    from app.email import send_email
    ...
    
    @blueprint.route('/mailer', methods=['GET', 'POST'])
    def mailer():
        user = current_user.full_name
        send_email(('name@gmail.com'),
                   'New mail', 'test.html',
                   user=user)
        return "Mail has been send."
    

    And when i call http://localhost:5000/mailer it starts countdown and after few seconds is mail sent.

提交回复
热议问题