Django: use fake SMTP server for debugging emails

Below you'll find a quick and easy tutorial on how to run your own instance of a fake SMTP server to debug your messages sent from the developed service.

Why is that so handy comparing to normal SMTP service or a custom Email Backend in Django?

Well.. it works as a real SMTP server, thus it will work with any SMTP client; We are not limited to our framework debugging capabilities and we can use it in any other application. The second thing is the development experience - simply seeing the message Subject and its contents as a real messages is just easier to monitor and navigate.

There are multiple fake SMTP servers that work in similar way, Mailtrap being the most popular, I guess. But I'd like to introduce something more suitable for our local development - Mailhog - an SMTP server that is easily installable on our docker-compose ecosystem.

Let's begin!

Add mailhog to your docker-compose file

services:
api:
depends_on:
- mailhog
// [...]

mailhog:
image: mailhog/mailhog:v1.0.0
ports:
- "8025:8025"

Note: it's good to mark mailhog as a dependency for the services that may need to send messages right from the start.

That's almost it! If you run your application and go to localhost:8025 you'll se the Mailhog messages interface. Each email message sent via Mailhog server will be shown here.

Let's now configure Django to sent messages via our fake SMTP:

Make Django work with Mailhog

The standard way

If you're not using django-environ, just add those few lines to the settings file:

# settings.py

# ...

EMAIL_HOST='mailhog'
EMAIL_PORT=1025

The django-environ way

If you're using django-environ package then instead of the above you can use a shortcut - first, set your ENV variable, e.g.

MAIL_URI=smtp://mailhog:1025

(meaning that the SMTP host name will be mailhog and it listens on port 1025.)

Now use django-environ's shortcut notation for email config:

# settings.py
EMAIL_CONFIG = env.email_url('EMAIL_URI')
vars().update(EMAIL_CONFIG)

Now you're ready to work with emails in your development environment.