Search code examples
pythondjangoadmin

Django does not send emails to admins on error 500


I have following settings in my Django project

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
DEFAULT_FROM_EMAIL = '[email protected]'
SERVER_EMAIL = '[email protected]'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'               #your acc and pass
EMAIL_HOST_PASSWORD = 'somepassword'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

ADMINS = (('myusername', '[email protected]'),)

But with this Django still does not send emails on 500 error to admins. What is wrong here? It is said in the docs that I should enter a full name to ADMINS settings. Is that full name from default User model? What if I have empty those fields? More to that - there is no validation that fields should be unique and there might be another people with the same name that admin has?

P.S. send_mail() from python shell works with those settings.

UPDATE My Logging settings:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'WARNING',
            'class': 'logging.FileHandler',
            'filename': os.path.join(BASE_DIR, 'debug.log'),
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'WARNING',
            'propagate': True,
        },
    },
}

Solution

  • In the LOGGING settings of settings.py add below block to handlers

                'mail_admins': {
                  'level': 'ERROR',
                  'class': 'django.utils.log.AdminEmailHandler'
            },
    

    Update:

    Add following line to above block only if emails to be sent when DEBUG is False.

                  'filters': ['require_debug_false'],
    

    and with following settings in filters sections

            'filters': {
               'require_debug_false': {
                  '()': 'django.utils.log.RequireDebugFalse',
               },
               'require_debug_true': {
                  '()': 'django.utils.log.RequireDebugTrue',
               },
            },  
    

    Update:

    Add mail_admin in handlers of loggers as below

            'loggers': {
              'django': {
                  'handlers': ['file', 'mail_admins'],
                  'level': 'INFO',
                  'propagate': True,
               },
             },