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
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.