Skip to content

Instantly share code, notes, and snippets.

@EyePulp
Last active December 13, 2015 19:28
Show Gist options
  • Save EyePulp/4962327 to your computer and use it in GitHub Desktop.
Save EyePulp/4962327 to your computer and use it in GitHub Desktop.
django templated e-mail using markdown/html -- supports attaching files or streaming file attachments
from django.conf import settings
def email_template(
template_name = None,
template_context = None,
subject = '',
recipients = None,
sender = settings.DEFAULT_FROM_EMAIL,
fail_silently = False,
use_markdown = False,
file_name_attachment_list = [],
file_pointer_attachment_list = [],
recipients_bcc = None,
headers = None
):
"""
simple method for e-mailing a rendered template file
use_markdown turns it into a multipart e-mail
with an html version derived from the markdown text of the template
`file_name_attachment_list` must be a list of full file paths (e.g. ['/foo/bar/baz/bet.jpg'])
`file_pointer_attachment_list` must be a list of 3-tuples of the form [('filename.jpg',file_pointer_data,'mime/type'),]
"""
print "Using new mailer"
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.template import loader, Context
if recipients is None:
recipients = []
if recipients_bcc is None:
recipients_bcc = []
text_part = loader.get_template(template_name)
subject_part = loader.get_template_from_string(subject)
if template_context is None:
context = Context({})
else:
context = Context(template_context)
text_part = text_part.render(context)
subject_part = subject_part.render(context)
if use_markdown: # do we want to produce an html version?
import markdown
html_part = markdown.markdown(text_part)
# log.info('markdown: %s...'%html_part[:150])
# print subject_part, text_part, sender, recipients,smtp
msg = EmailMultiAlternatives(
subject = subject_part,
body = text_part,
from_email = sender,
to = recipients,
bcc = recipients_bcc,
headers = headers,
)
msg.attach_alternative(html_part, "text/html")
else:
msg = EmailMessage(
subject = subject_part,
body = text_part,
from_email = sender,
to = recipients,
bcc = recipients_bcc,
headers = headers,
)
# loop through the file attachements if needed
if file_name_attachment_list:
for item in file_name_attachment_list:
msg.attach_file(item)
# loop through the file pointer attachments if needed
if file_pointer_attachment_list:
for item in file_pointer_attachment_list:
msg.attach(*item)
return msg.send(fail_silently=fail_silently)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment