Why does Django's send_mail not work during testing? Why does Django's send_mail not work during testing? django django

Why does Django's send_mail not work during testing?


Your config is being overruled

In Section "Email Services", the Django testing documentation says:

Django's test runner automatically redirects all Django-sent email to a dummy outbox. [...] During test running, each outgoing email is saved in django.core.mail.outbox. This is a simple list of all EmailMessage instances that have been sent.

Huh?

The Django test runner will actually configure a different email backend for you (called locmem).It is very convenient if you want to do unit-testing only(without integration with an actual email server), butvery surprising if you don't know it.

(I am not using the Django test runner manage.py test, but it happens anyway, presumably because I have pytest-django installed which magically modifies my py.test.)

If you want to override the overriding and use the email configurationgiven in your settings module, all you need to re-set is the setting for the email backend, e.g. like this:

@django.test.utils.override_settings(    EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend')def test_send_email_with_real_SMTP(self):   ...


It is probably worthwhile trying to turn this into a proper unit test, which of course you can then run as part of your automated test suite. For unit testing, probably the easiest way to check whether the mail was sent (and verify the contents of the mail if required) is to use Django's built-in in memory email backend - you can simply use the outbox attribute on this to get a list of sent mails:

https://docs.djangoproject.com/en/dev/topics/email/#in-memory-backend

This has the advantage of not requiring any infrastructure setup to support testing email sending, makes it very simple to assert the contents of your email, and this should also make the tests fast (when compared to actually sending the emails to an SMTP server).

Hope this helps.


From what I understand, you are running the following command while testing the unit.

python -m smtpd -n -c DebuggingServer localhost:1025

This command starts up a "dumb" SMTP server that recieves your emails and displays them on the terminal. Try running your site without this DebuggingServer set up and see if the mails are sent.

Here is the reference to the docs page