Rendering emails with Django templates

I talk a lot about Javascript on this blog: client-side, server-side, wherever the language can be used. It’s not the only language I enjoy working in, though; Python has always had a bit of a soft spot with me, and with that comes some inevitable Django love.

I use Django for a lot of my server side tasks where I don’t feel I can safely use something like Node.js. On top of being battle tested beyond belief, it’s a veritable bag of magic tricks just waiting to be used. Take this one case I ran into recently: I’m building a service (stealth at the moment, stay tuned) that has to do something as simple as send out an email when a new user signs up.

Now, that email should ideally contain a few things. Let’s assume that, for a basic example, we’re gonna just include their username, a brand new password, and their full name (how we’ll use each of these is shown in depth below). Django makes sending mail pretty easy, using the send_mail function:

That’s all well and good, but what if we want to do more than just a simple string for our body message? Ideally, we should be able to treat this like any other Django template. In practice, this is actually incredibly easy (and fun).

The code should be fairly well documented, but for those who’d like a little more verbose of a walkthrough, it’s pretty simple: instead of passing in a string, load up a template and pass it a rendering context. See, what got me the first time around is that the render method of get_template needs a Template Context to do the dirty work, not a standard dict.

With that, here’s an example of an email template – it’s literally just a Django template, but ready for all your email attributes.

Django’s templating system is incredibly flexible, and can easily be used for more than just your generic views. If you have any questions or suggestions, feel free to throw them in the comments!

4 Responses to “Rendering emails with Django templates”

  1. Dan says:

    This was great. Not at all a difficult task, but not documented as well as it should be. Thanks for this!

  2. Malhar Vora says:

    Great article. Very helpful to me.
    Can you please tell why I am getting raw html coding in email ?

  3. Marc Wilhelm says:

    I used this to render a template into a variable instead of sending it to the HTTP client. Thanks for this.

  4. Jorge Ortiz says:

    Thanks. I added some extra flexibility by using get_template_from_string() instead of get_template()
    This allows me to store my templates in the database as part of a model with a field of type models.TextField, rather than hardcoding it into a file.

Leave a Reply