Sandboxing emails in Django

by Sumit Chachra on July 10, 2010

Its usually good to sandbox your QA / staging environments so that they don’t shoot out emails to real email addresses (say you’ve made a copy of your production database). Django 1.2 and their email backends make it really easy to do so.


Here’s a testing email backend I wrote. Simply drop in a email address associated with the DEFAULT_TO_EMAIL setting in your settings.py. Also set the EMAIL_BACKEND in settings.py to the class below.


This also takes care of cases where in your code you’re sending a “mass mail” (using send_mass_mail), it’ll only send one out.
from django.core.mail.backends.smtp import EmailBackend
class TestingEmailBackend(EmailBackend):
    """
    Used in dev and qa
    """
    def send_messages(self, email_messages):
        """
        Overrides the to email address. Also if there are tons of messages being sent out then it reduces them to
        1 message.
        """
        if len(email_messages) > 1:
            email_messages = (email_messages[0],)
        email_messages[0].to = [django_settings.DEFAULT_TO_EMAIL,]
        super(TestingEmailBackend, self).send_messages(email_messages)
    blog comments powered by Disqus

    Previous post:

    Next post:

    Powered by Tivix