email reporting exceptions and errors using AdminEmailHandler and SMTPHandler

The Django doc says: In order to send email, EMAIL_HOST, EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are at the very least needed, but as I tested, we should also specify SERVER_EMAIL, and only when SERVER_EMAIL is equal to EMAIL_HOST_USER so can send the email, e.g.
EMAIL_HOST = 'smtp.163.com'  
SERVER_EMAIL = '234327894-cold@163.com'  # 
EMAIL_HOST_USER = '234327894-cold@163.com'  # 
EMAIL_HOST_PASSWORD = '234327894123'  #
Django uses AdminEmailHandler to send an email to the site admins for each log message it receives.
Besides Django, we could also use Python’s
logging.handlers.SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=1.0)
to do the same.
For example, put the following code in views.py(do change to your account), it will email reporting unhandled exceptions and results in an internal server error (HTTP status code 500).
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d %I:%M:%S %p', handlers=[logging.handlers.SMTPHandler('smtp.163.com', '234327894-cold@163.com', ['234327894-cold@163.com'], 'LYYDownloader Server Exception', credentials=('234327894-cold@163.com', '234327894123'))])
Comparing AdminEmailHandler and SMTPHandler, I advocate to use SMTPHandler whenever possible.
First, AdminEmailHandler is Django specific, while you can use SMTPHandler in any Python program, one thing you should care is when using SMTPHandler in client side software, some anti-virus software may treat the software as spyware, so you should inform users when your software is about to send email.
Second, I found email sending by AdminEmailHandler has a bunch of Information while SMTPHandler just send the Python exception Information which makes debugging a bit clear!

Third , If you configure your email within settings.py in Django , there is no exception throw out even If you have made something wrong with the email confirmation , while SMTPHandler always throw out exception on what’s wrong in using .

Comments

  1. I tried to setup django server notification with the following settings. But they are not working. Any idea how to troubleshoot?

    DEBUG = False
    ADMINS = [('Rama', 'rama@domain.com'), ('Bheema', 'bheema@domain.com'),]
    EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
    EMAIL_USE_TLS = True
    EMAIL_HOST = "smtp.gmail.com"
    EMAIL_PORT = 587
    SERVER_EMAIL = 'somebody@gmail.com'
    EMAIL_HOST_USER = "somebody@gmail.com"
    EMAIL_HOST_PASSWORD = ""

    ReplyDelete

Post a Comment