Printing emails in Django

by

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 settings.py and mails are now printed:

if DEBUG:
 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(message.to))
      print("tSubject: %s" % message.subject)
      print("t%s" % "nt".join(wrap(message.body)))
      print(messages)
      return len(messages)

And that’s it.

You may also like:

If you want to work with me or hire me? Contact me

You can follow me or connect with me:

Or get new content delivered directly to your inbox.

Join 5,047 other subscribers

I wrote a book:

Stack of copies of How to Hire and Manage Remote Teams

How to Hire and Manage Remote Teams, where I distill all the techniques I’ve been using to build and manage distributed teams for the past 10 years.

I write about:

announcement blogging book book review book reviews books building Sano Business C# Clojure ClojureScript Common Lisp database Debian Esperanto Git ham radio history idea Java Kubuntu Lisp management Non-Fiction OpenID programming Python Radio Society of Great Britain Rails rant re-frame release Ruby Ruby on Rails Sano science science fiction security self-help Star Trek technology Ubuntu web Windows WordPress

I’ve been writing for a while:

Mastodon