Skip to content

Instantly share code, notes, and snippets.

@diverru
Created March 11, 2020 08:41
Show Gist options
  • Save diverru/27d986583253e8d3c8f6ef7449096e4c to your computer and use it in GitHub Desktop.
Save diverru/27d986583253e8d3c8f6ef7449096e4c to your computer and use it in GitHub Desktop.
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