Sending welcome emails asynchronously in python Flask application Sending welcome emails asynchronously in python Flask application flask flask

Sending welcome emails asynchronously in python Flask application


You can do it with threads as shown in Grinberg's tutorial

from threading import Threaddef threading(f):    def wrapper(*args, **kwargs):        thr = Thread(target=f, args=args, kwargs=kwargs)        thr.start()    return wrapper@threadingdef send_email(subject, to, body, html=None):    def send():        try:            mail.send(msg)        except Exception as err:            app.logger.error("Error during mail send: {0}".format(err))    with app.app_context():        msg = Message(subject, recipients=[to], body=body, html=html,                      sender="welcome@myapp.net")        send()

And then in your view you can call send_email and not have to wait

If you want to incorporate feedback (aka live information in case there's an error when sending the email) for the email, you should add a message broker (i.e rabbitmq, zeromq) and a task queue (i.e celery) to the implementation (and a way to poll asynchronously for messages from the UI). Although I don't think you really need something like this for welcome emails -unless you send them in batches, you can find an example of how to use such stuff here