Multipart Templated Email

 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 <steve@jupo.org>

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. Email-obfuscator Template Tag by gronimo 1 year, 11 months ago
  2. Simple e-mail template tag by dchandek 5 years, 12 months ago
  3. hide emails with PIL - template filter by dekomote 4 years, 5 months ago
  4. Newsletter email template by jibbolo 2 years, 7 months ago
  5. Email Munger by cootetom 5 years, 3 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

#

(Forgotten your password?)