Printing emails in Django

When developing applications in Django, it may be nice to print emails instead of sending them. If you send them you have to be careful which addresses you use. Just being on the safe side and always using @example.{com,org,net} is not enough, you have to use an address you can actually retrieve emails for. And you have to configure your development environment to actually deliver mails. And then wait for the whole thing in each code-try iteration.

So, basing myself on the testing code, I’ve added this to and mails are now printed:

 from utils import BogusSMTPConnection
 from django.core import mail
 mail.SMTPConnection = BogusSMTPConnection

Of course you’ll also need the BogusSMTPConnection class, I’ve defined it as following:

from textwrap import wrap
class BogusSMTPConnection(object):
  """Instead of sending emails, print them to the console."""

  def __init__(*args, **kwargs):
    print("Initialized bogus SMTP connection")

  def open(self):
    print("Open bogus SMTP connection")

  def close(self):
    print("Close bogus SMTP connection")

  def send_messages(self, messages):
    print("Sending through bogus SMTP connection:")
    for message in messages:
      print("tFrom: %s" % message.from_email)
      print("tTo: %s" % ", ".join(
      print("tSubject: %s" % message.subject)
      print("t%s" % "nt".join(wrap(message.body)))
      return len(messages)

And that’s it.

6 thoughts on “Printing emails in Django

  1. This was really helpful, thanks. I was dreading the thought of setting up an SMTP server just to send emails I didn’t care about.

  2. Just a nit, but I assume in the close method above you meant to print(“Close….) not clone.

  3. Have you tried this:
    python -m smtpd -n -c DebuggingServer localhost:1025

    This will catch everything and redirect the input into standard out, which you can redirect if you want of course.

    Can’t claim credit, my fellow worker showed me. :)

  4. FYI in Django 1.2 mail.SMTPConnection is deprecated, and this little trick no longer works. I don’t have a replacement solution yet, but I’ll post it here if I find one.

  5. Ok, so this got much easier as of Django 1.2. Instead of writing your own class, just throw this in your

    if DEBUG:
    EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

    See the rest of the options here.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.