Django not sending emails to admins
According to the documentation, if DEBUG
is set to False
and something is provided under the ADMINS
setting, Django will send an email whenever the code raises a 500 status code. I have the email settings filled out properly (as I can use send_mail fine) but whenever I intentionally put up erroneous code I get my 500.html template but no error email is sent. What could cause Django to not do this?
Solution 1:
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]'
Solution 2:
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).
Solution 3:
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.
Solution 4:
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.
Solution 5:
My web hosting provider - Webfaction - only allows emails to be sent From an email that has been explicitly created in the administrator panel. Creating one fixed the problem.