all that is technology

Using mail during django development


While developing a module that requires to send emails, using actual email servers would be an overhead. They might introduce network latency, possible spam filtering etc. All end up retarding productivity.

We have smtpd.DebuggingServer that could be used as a local email server. All emails that are sent to this server outputs to the stdout. To start the server.

$ python -m smtpd -n -c DebuggingServer localhost:1025

and the corresponding setting to be used in is

EMAIL_HOST = 'localhost'

The code snippet that sends the mail is below.

from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.html import strip_tags

subject, from_email = 'Account created', ''
html_content = render_to_string('email.html')
text_content = strip_tags(html_content)
msg = EmailMultiAlternatives(subject, text_content, from_email, [])
msg.attach_alternative(html_content, 'text/html')

Upon calling send message, the mail would be delivered to the DebuggingServer and displayed in stdout as below.

---------- MESSAGE FOLLOWS ----------
Content-Type: multipart/alternative; boundary="===============0236101087=="
MIME-Version: 1.0
Subject: Account created
Date: Thu, 09 May 2013 05:53:21 -0000

Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

Mail sent from

Account created.

Content-Type: text/html; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

<p>Mail sent from</p>
<div style="background: #ddd;border: 1px solid #d3d3d3;-moz-border-radius: 3px;border-radius: 3px;width: 50%;line-height: 100px;text-align: center;">
Account created.
------------ END MESSAGE ------------

Hope this helps.