Last active
August 29, 2015 14:05
-
-
Save theY4Kman/267489836f190a1fe270 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import os | |
| from django.conf import settings | |
| from django.core.mail.message import EmailMultiAlternatives | |
| from django.template.base import TemplateDoesNotExist | |
| from django.template.loader import render_to_string | |
| def email_from_template(template_dir, ctx=None, from_email=None, to=None): | |
| """Generate an Email message from a set of templates | |
| An email is generated by rendering the following templates in the provided | |
| template directory using the provided context (ctx): | |
| - body.txt (text body) | |
| - body.html (full html body) | |
| - subject.txt (text subject) | |
| The subject.txt and body.html must always be included. If body.txt is not | |
| included, body.html is used. This is bad! BE SURE TO INCLUDE A TEXT | |
| TEMPLATE FOR ACCESSIBILITY. | |
| Note: the message is NOT sent. | |
| """ | |
| if ctx is None: | |
| ctx = {} | |
| _rel = lambda *parts: os.path.join(template_dir, *parts) | |
| subject = render_to_string(_rel('subject.txt'), ctx) | |
| # Subject cannot have newlines | |
| subject = subject.replace('\n', '').replace('\r', '') | |
| message = EmailMultiAlternatives(subject, '', from_email, to) | |
| body_html = render_to_string(_rel('body.html'), ctx) | |
| try: | |
| body_txt = render_to_string(_rel('body.txt'), ctx) | |
| except TemplateDoesNotExist: | |
| message.content_subtype = 'html' | |
| message.body = body_html | |
| else: | |
| message.body = body_txt | |
| message.attach_alternative(body_html, 'text/html') | |
| return message | |
| def send_from_template(template_dir, ctx=None, from_email=None, to=None, | |
| fail_silently=False): | |
| if from_email is None: | |
| from_email = settings.DEFAULT_FROM_EMAIL | |
| message = email_from_template(template_dir, ctx, from_email, to) | |
| return message.send(fail_silently=fail_silently) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment