Skip to content

Instantly share code, notes, and snippets.

Last active Apr 14, 2020
What would you like to do?
A wrapper around Django's EmailMultiAlternatives that renders templates.
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
class EMail(object):
A wrapper around Django's EmailMultiAlternatives
that renders txt and html templates.
Example Usage:
>>> email = Email(to='', subject='A great non-spammy email!')
>>> ctx = {'username': 'Oz Katz'}
>>> email.text('templates/email.txt', ctx)
>>> email.html('templates/email.html', ctx) # Optional
>>> email.send()
def __init__(self, to, subject): = to
self.subject = subject
self._html = None
self._text = None
def _render(self, template, context):
return render_to_string(template, context)
def html(self, template, context):
self._html = self._render(template, context)
def text(self, template, context):
self._text = self._render(template, context)
def send(self, from_addr=None, fail_silently=False):
if isinstance(, basestring): = []
if not from_addr:
from_addr = getattr(settings, 'EMAIL_FROM_ADDR')
msg = EmailMultiAlternatives(
if self._html:
msg.attach_alternative(self._html, 'text/html')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment