How To Send Email In Flask Asynchronously

Learn to send emails in Flask asynchronously

· 1 min read
How To Send Email In Flask Asynchronously

Are you trying to send emails with the Flask framework? And is it taking too much time to give a 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 a ‘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 emails 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 projects.

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