Prasobhraj
Prasobhraj

Reputation: 85

How to send emails in background in python webapplication with flask framework?

I need to sent emails to large number of recipients with attachments from my web application after completing an event. So I want to run this in the background in order to not affect main application processes. How to implement this?

Upvotes: 3

Views: 2020

Answers (1)

jumbopap
jumbopap

Reputation: 4137

Miguel Grinberg gives a complete example of this in his Flask Mega Tutorial.

Basically you can push your mail sending to another thread.

from threading import Thread
from app import app

def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)

def send_email(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()

Upvotes: 3

Related Questions