Django: Sending mail with Templates
It’s interesting how only a few lines of code can save so much work. A few days ago, I was working on adding a new feature to a system I wrote a while ago using django. I noticed there were a few places that I wanted to send out an email along with logging. I started looking into Django’s ability to send out emails, after much searching I found the mail_admins function. I wasn’t a huge fan of having the email content buried in the code. I did a few quick searches on the documentation and came up with no real solutions. Using Django’s render_to_response as an example I created a function that would allow me to send an email using a Django template.
from django.template import loader
from django.core.mail import mail_admins
def render_to_email(template, subject, context):
template = loader.render_to_string(template, context)
mail_admins(subject, template)
The function works exactly like Django’s render_to_response function, with one added value to the function for setting the email’s subject
render_to_email('email_general_error.html', 'General Error', { 'request': request, 'message': message})
