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.
In this tutorial, I am going to use these python modules
- Yagmail — for sending email
- 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
pip install yagmail
pip install celery
If you are in windows you also want to install ‘eventlet’, because ‘celery’ has stopped support for windows.
pip install eventlet
For Windows, you can download the latest installer from the given link.
For Linux, you can directly use this command.
sudo apt-get install -y rabbitmq-server
Use the given link to get the complete setup guide for various Linux distributions.
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.