Blog

The Digital Agency for International Development

Sending email from Django

By Chris Wilson on 29 March 2012

Yesterday I wanted to send email notifications for document changes in the Generic Intranet. I found that the built-in Django method requires you to hard-code the email body. It doesn't support rendering email from templates, unlike Ruby on Rails, which is surprising and a shame.

I spent some time coding template support for it, and then when I tried to make it reusable, discovered that others had had the same idea.

Learning 1:
django is conservative. Lots of useful things never make it into the core. Search djangopackages.com for what you want before writing it. It has a LOT of packages.

Learning 2:
there's an existing document management package called Mayan EDMS, that does most of what ours does, which we could look at replacing or merging ours with.

I found two email-sending packages that support templates:

I decided to check out the object-oriented one, on a pretty much random basis, and add tests to it. You can find my fork of it here.

Learning 3:
If you want to send emails from a Django project, use our email app.

Learning 4:
if you want to send notifications in some kind of generic framework, not just email, have a look at the django-notification app instead.

Learning 5 (meta-learning):
it's useful to email round things that we discovered, like this one, as someone might have discovered this before and not told anyone, meaning that I had to spend time discovering it again; and also we can comment on each others' discoveries and add to them.

Oct. 2, 2012, 10:29 p.m. - Frank Stallone

I recently needed to add functionality to a Django application for sending and receiving email. Django does have good mail support, especially with contributions such as your own. But I've been finding Flask makes more sense for a lot of projects I'm doing. So for the sake of reusability I worked directly with the python email libraries and made something generic so I can use the code in Django or Flask. I used jinja templates but really anything could be used. I'm going to tidy up the source code a bit and release it. Python is one of the nicest languages to work with in terms of email (or anything). Fortunately everything you need is built into it.