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.
Add mailhog to your docker-compose file
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:
If you're using
django-environ package then instead of the above you can use a shortcut - first, set your ENV variable, e.g.
(meaning that the SMTP host name will be
mailhog and it listens on port
django-environ's shortcut notation for email config:
EMAIL_CONFIG = env.email_url('EMAIL_URI')
Now you're ready to work with emails in your development environment.