Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django not sending emails to admins

Tags:

python

django

In my case the cause was missing SERVER_EMAIL setting.

The default for SERVER_EMAIL is root@localhost. But many of email servers including my email provider do not accept emails from such suspicious addresses. They silently drop the emails.

Changing the sender email address to [email protected] solved the problem. In settings.py:

SERVER_EMAIL = '[email protected]'

Another possibility for error is trouble with your ADMINS setting. The following setting will cause the sending of mail to admins to fail quietly:

ADMINS = (
  ('your name', '[email protected]')
)

What's wrong with that? Well ADMINS needs to be a tuple of tuples, so the above needs to be formatted as

ADMINS = (
  ('your name', '[email protected]'),
)

Note the trailing comma. Without the failing comma, the 'to' address on the email will be incorrectly formatted (and then probably discarded silently by your SMTP server).


I had the same situation. I created a new project and app and it worked, so I knew it was my code. I tracked it down to the LOGGING dictionary in settings.py. I had made some changes a few weeks back for logging with Sentry, but for some reason the error just started today. I changed back to the original and got it working:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

Then, I made some changes slowly and got it working with Sentry and emailing the ADMINS as well.

Additionally, the LOGGING configuration gets merged with DEFAULT_LOGGING by default, so it's useful to have a look at the source code of django.utils.log.DEFAULT_LOGGING to understand what else may have an effect on your particular situation.


Make sure your EMAIL_HOST and EMAIL_PORT are set up right in settings.py (these refer to your SMTP server). It might be assuming that you have an SMTP server running on localhost.

To test this locally, run Python's built-in test SMTP server:

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

Then set these values in your settings.py

EMAIL_HOST='localhost'
EMAIL_PORT=1025

Trigger a 500 error, and you should see the e-mail appear in the python smtpd terminal window.