Login

Multipart Templated Email

Author:
stephen_mcd
Posted:
February 24, 2010
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
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 <[email protected]>

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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

darb (on April 26, 2011):

Currently maintaining a library to make this stuff even easier (able to switch between using django templates for email, and using a provider like postageapp for sending), see django-templated-email

#

Please login first before commenting.