How To Send Email In Flask Asynchronously

Shashikant Dwivedi
SKDBLOG
Published in
2 min readMar 24, 2020

--

Are you trying to send emails with flask framework ? And is it taking too much time to give response ?

This tutorial will show you how you can send emails with flask without any waiting time.

So let's start.

Environment Setup

In this tutorial, I am going to use these python modules

  1. yagmail — for sending email
  2. celery — for queueing the tasks

And we also need ‘RabbitMQ’ message broker that is used by celery to complete its process.

If you are working on a virtual environment then activate it and start the process

Installing yagmail

pip install yagmail

Installing celery

pip install celery

If you are in windows you also want to install ‘eventlet’, because ‘celery’ has stopped support for windows.

pip install eventlet

Installing RabbitMQ

For Windows, you can download the latest installer from the given link.

https://www.rabbitmq.com/install-windows.html

For Linux, you can directly use this command.

sudo apt-get install -y rabbitmq-server

OR

Use the given link to get the complete setup guide for various Linux distributions.

https://www.rabbitmq.com/download.html

Code

Before start sending email asynchronously, you have to start the celery worker.

To start celery on cmd/terminal on the project directory where the ‘send_email.py’ file is located and activate the virtual environment if any.

celery -A send_mail worker -l=info

And if you are on windows use this command

celery -A send_mail worker -l=info -P eventlet

After this just run your python file and it will start sending the emails asynchronously.

You can also save the send_email.py and use it in as many as projects.

If you have any doubt you can ask me in the comment section.

--

--

Shashikant Dwivedi
SKDBLOG

I am full time developer, working for DeviceDoctor.IN. I write articles on topics that I learn daily by doing.