Debian Codegraph @

templated_email/backends/vanilla_django.py

raw
1 import uuid
2 import hashlib
3 from io import BytesIO
4
5 from django.conf import settings
6 from django.core.mail import get_connection
7 from django.template import Context
8 from django.utils.translation import gettext as _
9 from django.core.files.storage import default_storage
10
11 from templated_email.utils import (
12 get_emailmessage_klass, get_emailmultialternatives_klass)
13 from templated_email.utils import InlineImage
14 from render_block import render_block_to_string, BlockNotFound
15
16
17 try:
18 import html2text
19 except ImportError:
20 html2text = None
21
22
23 class EmailRenderException(Exception):
24 pass
25
26
27 class TemplateBackend(object):
28 """
29 Backend which uses Django's
30 templates, and django's send_mail function.
31
32 Heavily inspired by http://stackoverflow.com/questions/2809547/creating-email-templates-with-django
33
34 Default / preferred behaviour works like so:
35 templates named
36 templated_email/<template_name>.email
37
38 {% block subject %} declares the subject
39 {% block plain %} declares text/plain
40 {% block html %} declares text/html
41
42 Legacy behaviour loads from:
43 Subjects for email templates can be configured in one of two ways:
44
45 * If you are using internationalisation, you can simply create entries for
46 "<template_name> email subject" as a msgid in your PO file
47
48 * Using a dictionary in settings.py, TEMPLATED_EMAIL_DJANGO_SUBJECTS,
49 for e.g.:
50 TEMPLATED_EMAIL_DJANGO_SUBJECTS = {
51 'welcome':'Welcome to my website',
52 }
53
54 Subjects are templatable using the context, i.e. A subject
55 that resolves to 'Welcome to my website, %(username)s', requires that
56 the context passed in to the send() method contains 'username' as one
57 of it's keys
58 """
59
60 def __init__(self, fail_silently=False,
61 template_prefix=None, template_suffix=None, **kwargs):
62 self.template_prefix = template_prefix or getattr(settings, 'TEMPLATED_EMAIL_TEMPLATE_DIR', 'templated_email/')
63 self.template_suffix = template_suffix or getattr(settings, 'TEMPLATED_EMAIL_FILE_EXTENSION', 'email')
64
65 def attach_inline_images(self, message, context):
66 for value in context.values():
67 if isinstance(value, InlineImage):
68 value.attach_to_message(message)
69
70 def host_inline_image(self, inline_image):
71 from templated_email.urls import app_name
72 md5sum = hashlib.md5(inline_image.content).hexdigest()
73
74 filename = inline_image.filename
75 filename = app_name + '/' + md5sum + filename
76 if not default_storage.exists(filename):
77 filename = default_storage.save(filename,
78 BytesIO(inline_image.content))
79 return default_storage.url(filename)
80
81 def _render_email(self, template_name, context,
82 template_dir=None, file_extension=None):
83 response = {}
84 errors = {}
85
86 file_extension = file_extension or self.template_suffix
87 if file_extension.startswith('.'):
88 file_extension = file_extension[1:]
89 template_extension = '.%s' % file_extension
90
91 if isinstance(template_name, (tuple, list, )):
92 prefixed_templates = template_name
93 else:
94 prefixed_templates = [template_name]
95
96 full_template_names = []
97 for one_prefixed_template in prefixed_templates:
98 one_full_template_name = ''.join((template_dir or self.template_prefix, one_prefixed_template))
99 if not one_full_template_name.endswith(template_extension):
100 one_full_template_name += template_extension
101 full_template_names.append(one_full_template_name)
102
103 for part in ['subject', 'html', 'plain']:
104 render_context = Context(context, autoescape=(part == 'html'))
105 try:
106 response[part] = render_block_to_string(full_template_names, part, render_context)
107 except BlockNotFound as error:
108 errors[part] = error
109
110 if response == {}:
111 raise EmailRenderException("Couldn't render email parts. Errors: %s"
112 % errors)
113
114 return response
115
116 def get_email_message(self, template_name, context, from_email=None, to=None,
117 cc=None, bcc=None, headers=None,
118 template_prefix=None, template_suffix=None,
119 template_dir=None, file_extension=None,
120 attachments=None, create_link=False):
121
122 if create_link:
123 email_uuid = uuid.uuid4()
124 link_context = dict(context)
125 context['email_uuid'] = email_uuid.hex
126 for key, value in context.items():
127 if isinstance(value, InlineImage):
128 link_context[key] = self.host_inline_image(value)
129
130 EmailMessage = get_emailmessage_klass()
131 EmailMultiAlternatives = get_emailmultialternatives_klass()
132 parts = self._render_email(template_name, context,
133 template_prefix or template_dir,
134 template_suffix or file_extension)
135 plain_part = 'plain' in parts
136 html_part = 'html' in parts
137
138 if create_link and html_part:
139 static_html_part = self._render_email(
140 template_name, link_context,
141 template_prefix or template_dir,
142 template_suffix or file_extension)['html']
143 from templated_email.models import SavedEmail
144 SavedEmail.objects.create(content=static_html_part, uuid=email_uuid)
145
146 if 'subject' in parts:
147 subject = parts['subject']
148 else:
149 subject_dict = getattr(settings, 'TEMPLATED_EMAIL_DJANGO_SUBJECTS', {})
150 if isinstance(template_name, (list, tuple)):
151 for template in template_name:
152 if template in subject_dict:
153 subject_template = subject_dict[template]
154 break
155 else:
156 subject_template = _('%s email subject' % template_name[0])
157 else:
158 subject_template = subject_dict.get(template_name,
159 _('%s email subject' % template_name))
160 subject = subject_template % context
161 subject = subject.strip('\n\r') # strip newlines from subject
162
163 if not plain_part:
164 plain_part = self._generate_plain_part(parts)
165
166 if plain_part and not html_part:
167 e = EmailMessage(
168 subject,
169 parts['plain'],
170 from_email,
171 to,
172 cc=cc,
173 bcc=bcc,
174 headers=headers,
175 attachments=attachments,
176 )
177
178 elif html_part and not plain_part:
179 e = EmailMessage(
180 subject,
181 parts['html'],
182 from_email,
183 to,
184 cc=cc,
185 bcc=bcc,
186 headers=headers,
187 attachments=attachments,
188 )
189 e.content_subtype = 'html'
190
191 elif plain_part and html_part:
192 e = EmailMultiAlternatives(
193 subject,
194 parts['plain'],
195 from_email,
196 to,
197 cc=cc,
198 bcc=bcc,
199 headers=headers,
200 attachments=attachments,
201 )
202 e.attach_alternative(parts['html'], 'text/html')
203
204 else:
205 raise EmailRenderException("Please specify at a plain and/or html block.")
206
207 self.attach_inline_images(e, context)
208 return e
209
210 def _generate_plain_part(self, parts):
211 """
212 Depending on some settings, generate a plain part from the HTML part.
213
214 The user can choose a custom "plain function" that takes an argument
215 of the HTML part and returns the plain text. By default this is
216 "html2text.html2text".
217 """
218 html_part = 'html' in parts
219 auto_plain = getattr(settings, 'TEMPLATED_EMAIL_AUTO_PLAIN', True)
220 plain_func = getattr(settings, 'TEMPLATED_EMAIL_PLAIN_FUNCTION', None)
221
222 if not auto_plain:
223 return
224
225 if not html_part:
226 return
227
228 if not plain_func and html2text:
229 plain_func = html2text.html2text
230
231 if not plain_func:
232 return
233
234 parts['plain'] = plain_func(parts['html'])
235 return True
236
237 def send(self, template_name, from_email, recipient_list, context,
238 cc=None, bcc=None,
239 fail_silently=False,
240 headers=None,
241 template_prefix=None, template_suffix=None,
242 template_dir=None, file_extension=None,
243 auth_user=None, auth_password=None,
244 connection=None, attachments=None,
245 create_link=False, **kwargs):
246
247 connection = connection or get_connection(username=auth_user,
248 password=auth_password,
249 fail_silently=fail_silently)
250
251 e = self.get_email_message(template_name, context, from_email=from_email,
252 to=recipient_list, cc=cc, bcc=bcc, headers=headers,
253 template_prefix=template_prefix,
254 template_suffix=template_suffix,
255 template_dir=template_dir,
256 file_extension=file_extension,
257 attachments=attachments,
258 create_link=create_link)
259
260 e.connection = connection
261
262 try:
263 e.send(fail_silently)
264 except NameError:
265 raise EmailRenderException("Couldn't render plain or html parts")
266
267 return e.extra_headers.get('Message-Id', None)