-
-
Save diverru/27d986583253e8d3c8f6ef7449096e4c to your computer and use it in GitHub Desktop.
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
def make_email(template_path, template_name, subject, context, to, from_email=None): | |
body_text_template, body_html_template = [ | |
"{}/{}.{}".format(template_path, template_name, ext) | |
for ext in ["txt", "html"] | |
] | |
try: | |
body_html = render_to_string(body_html_template, context) | |
body_html = premailer.transform(body_html, base_url=settings.HOME_URL) | |
# if email_track: | |
# body_html = transform_attributes(body_html, 'a', 'href', | |
# lambda href: email_track.add_email_track_key(href)) | |
body_html = mark_safe(body_html) | |
except TemplateDoesNotExist: | |
body_html = None | |
try: | |
body_text = render_to_string(body_text_template, context) | |
except TemplateDoesNotExist: | |
if body_html: | |
body_text = html2text.html2text(body_html) | |
else: | |
body_text = None | |
from_ = from_email or settings.DEFAULT_FROM_EMAIL | |
headers = ({'List-Unsubscribe': '<{}>'.format(context['unsubscribe_url'])} | |
if 'unsubscribe_url' in context else None) | |
if body_text and body_html: | |
email = EmailMultiAlternatives(subject, body_text, from_, to, headers=headers) | |
email.attach_alternative(body_html, 'text/html') | |
elif body_text: | |
email = EmailMessage(subject, body_text, from_, to, headers=headers) | |
elif body_html: | |
email = EmailMessage(subject, body_html, from_, to, headers=headers) | |
email.content_subtype = "html" | |
else: | |
raise TemplateDoesNotExist("No template {}".format(template_name)) | |
return email |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment