Using MailHog with Django
What do you use as the EMAIL_BACKEND
in Django during development?
I use django.core.mail.backends.console.EmailBackend
. But, in some cases, it turns out to be not good enough. For example, consider the situations where we would want to test the UI aspects of the emails?
So, one fine day, while searching for alternative options, I came across MailHog.
In this short article, I am going to introduce you to MailHog and how to use it with Django.
In brief, MailHog is an email testing tool for developers that allows us to view emails in a web UI, or retrieve them via a JSON API.
So, using MailHog during development, you would be receiving emails in a web UI —
You can find the official code repository of MailHog here at GitHub. The README
offers more insight on it’s features and usage.
Now, how to use MailHog with Django? Just three simple steps —
- Download the latest release of MailHog for your platform from here. It’s v1.0.0 at the time of writing.
- Execute the downloaded file.
In Linux, you would need to traverse to the directory where you downloaded the executable —MailHog_linux_amd64
(64-bit) orMailHog_linux_386
(32-bit) and use the command —./MailHog_linux_amd64
or./MailHog_linux_386
to execute. In either case, you would get an output similar to this —
0.0.0.0:1025
and a HTTP server which is bound to the address — 0.0.0.0:8025
.- Add/update the following lines in your project’s
settings.py
—
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 127.0.0.1
EMAIL_PORT = 1025
Please note that you should fetch settings parameters from the environment instead of hard-coding them. You can read more about it here.
I hard-coded them in order to make the changes required easier to understand.
After making the changes, all the emails sent will be available in a web UI at https://127.0.0.1:8025. Try yourself!
That’s it.
Endnotes:
- If you are unable to execute the downloaded binary (on Linux platform), it’s possible that you do not have execute permission over the binary. Provide yourself with the permission to execute the binary via the command —
chmod u+x MailHog_linux_amd64
. - Some alternatives to MailHog include MailCatcher and Mailtrap. Their usage with Django will, most probably, be the same as described in this article.