frnhr frnhr - 3 months ago 28
Python Question

Manually trigger Django email error report

Django error reporting handles uncaught exceptions by sending an email, and (optionally) shows user a nice 500 error page.

This works very well, but in a few instances I'd like to allow users to continue with their business uninterrupted, but still have Django send me the email error report about the exception.

So basically: can I manually send email error report even if I catch the exception?

Of course, I'd like to avoid manually generating the error report email.


You can use the following code to send manually an email about a request and an exception e:

import sys
import traceback
from django.core import mail
from django.views.debug import ExceptionReporter

def send_manually_exception_email(request, e):
    exc_info = sys.exc_info()
    reporter = ExceptionReporter(request, is_email=True, *exc_info)
    subject = e.message.replace('\n', '\\n').replace('\r', '\\r')[:989]
    message = "%s\n\n%s" % (
        subject, message, fail_silently=True,

You can test it in a view like this:

def test_view(request):
        raise Exception
    except Exception as e:
        send_manually_exception_email(request, e)