I’m writing unit tests for my django app and I was wondering if there are any packages for mocking email or if there
is any way I could mock sending and receiving of emails.
Basically what Django does when you run your test suite is switch your EMAIL_BACKEND to
django.core.mail.backends.locmem.EmailBackend, so to prevent your application from sending emails during the tests
While using this backend, all emails sent are stored in the outbox attribute of the django.core.mail module.
Let’s see one example on how you can use it to test the email outputs and so on.
This is a simple view that expects a querystring parameter named email with a valid email address. If the email value
fulfill our view requirements, an email is sent to this address. If the email is invalid or no email is provided at
all, the view just return a message for the user.
Now, let’s write some unit tests for it. First, a test case in case no email is provided:
We can also write a test case and inspect the email contents: