Testing email sending in Django [closed] Testing email sending in Django [closed] python python

Testing email sending in Django [closed]


Django test framework has some built in helpers to aid you with testing e-mail service.

Example from docs (short version):

from django.core import mailfrom django.test import TestCaseclass EmailTest(TestCase):    def test_send_email(self):        mail.send_mail('Subject here', 'Here is the message.',            'from@example.com', ['to@example.com'],            fail_silently=False)        self.assertEqual(len(mail.outbox), 1)        self.assertEqual(mail.outbox[0].subject, 'Subject here')


You can use a file backend for sending emails which is a very handy solution for development and testing; emails are not sent but stored in a folder you can specify!


If you are into unit-testing the best solution is to use the In-memory backend provided by django.

EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

Take the case of use it as a py.test fixture

@pytest.fixture(autouse=True)def email_backend_setup(self, settings):    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'  

In each test, the mail.outbox is reset with the server, so there are no side effects between tests.

from django.core import maildef test_send(self):    mail.send_mail('subject', 'body.', 'from@example.com', ['to@example.com'])    assert len(mail.outbox) == 1def test_send_again(self):    mail.send_mail('subject', 'body.', 'from@example.com', ['to@example.com'])    assert len(mail.outbox) == 1