Last active
April 14, 2020 20:03
-
-
Save ozkatz/5520308 to your computer and use it in GitHub Desktop.
A wrapper around Django's EmailMultiAlternatives that renders templates.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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='[email protected]', 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): | |
self.to = 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(self.to, basestring): | |
self.to = [self.to] | |
if not from_addr: | |
from_addr = getattr(settings, 'EMAIL_FROM_ADDR') | |
msg = EmailMultiAlternatives( | |
self.subject, | |
self._text, | |
from_addr, | |
self.to | |
) | |
if self._html: | |
msg.attach_alternative(self._html, 'text/html') | |
msg.send(fail_silently) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment