Testing email sending in Django

RadiantHex picture RadiantHex · Sep 16, 2010 · Viewed 43.5k times · Source

I need to test that my Django application sends e-mails with correct content. I don't want to rely on external systems (like an ad-hoc gmail account), since I'm not testing the actual e-mail service...

I would like to, maybe, store the emails locally, within a folder as they are sent. Any tip on how to achieve it?

Answer

Davor Lucic picture Davor Lucic · Sep 16, 2010

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 mail
from django.test import TestCase

class EmailTest(TestCase):
    def test_send_email(self):
        mail.send_mail('Subject here', 'Here is the message.',
            '[email protected]', ['[email protected]'],
            fail_silently=False)
        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, 'Subject here')