Menu Close

How to send emails through a Docker container using Flask API?

In this tutorial, we will use Docker to run a container for our email api.

I had some small projects that required a local mail server to send alerts or other types of emails.

Back in the day, my projects were written in PHP and then as a simple solution, I’ve been using Postfix with its basic configuration. Postfix is a simple email server, easy to administer and secure.

But, what if you don’t need a whole email server just for sending some emails? Yeah, you don’t!

What you just need is a service, a service that can send emails to a destination. As a workaround, I have made a small project in Python using Flask to handle emails.

Docker and Flask mailer

Flask mailer is an API made in Python with Flask that sends emails over an SMTP Google account. How does this work?

The service will expose an endpoint that accepts POST requests with the following JSON arguments: to, subject and body. In other words, it will assemble the email and using an existing Google account it will send it further to its destination.

What you’ll need?

Mainly Docker installed and my docker image of the service itself. The image is listed on Docker Hub right here. There is a short info, however, I will show the step by step guide to make it work and to send your first email using this service.

Pull the flask mailer image from Docker Hub:

docker pull skykery/api_mail

Launch a docker container that forwards port 9505 to 9505 with the following environment variables API_MAIL_USER and API_MAIL_PASS.

API_MAIL_USER it is the email address you want to send the email

API_MAIL_PASS the password of the used email address

docker run -p 9505:9505 -e API_MAIL_USER="" -e API_MAIL_PASS="test" --name flask_mailer skykery/api_mail

If it works, you’ll be seeing:

Docker running flask container
If you don’t want to block the terminal, launch the container in the foreground adding -d option to the docker run command.

To stop the container use:

docker stop flask_mailer

Example of sending an email through our service

curl -X POST -d '{"to":"", "subject": "Hello from flask", "body": "Hmm, seems it is working!"}' -H "Content-Type: application/json"
As you can see the response is a JSON containing the success status.

Don’t forget to turn off your security checks on the used Google account – How to turn on Less secure app access on used Google Account?

If you are curious about Flask mailer source code, navigate to the Github project.

Now, you can use the service with any project you want, have fun!

Spread the love

Leave a Reply