""" A replacement for sending mail that takes the name of a template which exists in both text and html formats, and uses these to create a multipart email populated with the given context. Credits: -------- Stephen McDonald License: -------- Creative Commons Attribution-Share Alike 3.0 License http://creativecommons.org/licenses/by-sa/3.0/ When attributing this work, you must maintain the Credits paragraph above. """ def send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=False): """ Send email rendering text and html versions for the specified template name using the context dictionary passed in. Arguments are as per django's send_mail apart from template which should be the common path and name of the text and html templates without the extension, for example: "email_templates/contact" where both "email_templates/contact.txt" and "email_templates/contact.html" exist. """ if context is None: context = {} if attachments is None: attachments = [] # allow for a single address to be passed in if not hasattr(addr_to, "__iter__"): addr_to = [addr_to] # loads a template passing in vars as context render = lambda type: loader.get_template("%s.%s" % (template, type)).render(Context(context)) # create and send email msg = EmailMultiAlternatives(subject, render("txt"), addr_from, addr_to) msg.attach_alternative(render("html"), "text/html") for attachment in attachments: msg.attach(attachment) msg.send(fail_silently=fail_silently)