-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathemail_utils.py
77 lines (66 loc) · 3.04 KB
/
email_utils.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Part of code from https://github.com/pennersr/django-allauth/
# The MIT License (MIT)
# Copyright (c) 2010-2017 Raymond Penners and contributors
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.core.mail import EmailMultiAlternatives
from django.template import TemplateDoesNotExist
from django.template.loader import render_to_string
from django.utils.encoding import force_text
def format_email_subject(subject, prefix=None):
if prefix is None:
site = get_current_site()
prefix = "[{name}] ".format(name=site.name)
return prefix + force_text(subject)
def render_mail(template_prefix, email, context, bcc=[], add_default_subj_pref=True):
"""
Renders an e-mail to `email`. `template_prefix` identifies the
e-mail that is to be sent, e.g. "account/email/email_confirmation"
"""
subject = render_to_string('{0}_subject.txt'.format(template_prefix),
context)
# remove superfluous line breaks
subject = " ".join(subject.splitlines()).strip()
subject = format_email_subject(subject, settings.EMAIL_SUBJECT_PREFIX if add_default_subj_pref else '')
bodies = {}
for ext in ['html', 'txt']:
try:
template_name = '{0}_message.{1}'.format(template_prefix, ext)
bodies[ext] = render_to_string(template_name,
context).strip()
except TemplateDoesNotExist:
if ext == 'txt' and not bodies:
# We need at least one body
raise
if 'txt' in bodies:
msg = EmailMultiAlternatives(subject,
bodies['txt'],
settings.DEFAULT_FROM_EMAIL,
email if isinstance(email, list) else [email],
bcc=bcc if isinstance(bcc, list) else [bcc]
)
if 'html' in bodies:
msg.attach_alternative(bodies['html'], 'text/html')
else:
msg = EmailMessage(subject,
bodies['html'],
settings.DEFAULT_FROM_EMAIL,
email if isinstance(email, list) else [email],
bcc=bcc if isinstance(bcc, list) else [bcc]
)
msg.content_subtype = 'html' # Main content is now text/html
return msg
def send_templated_mail(template_prefix, email, context, bcc=[], add_default_subj_pref=True):
msg = render_mail(template_prefix, email, context, bcc)
msg.send()
def send_custom_mail(subj, body, email, bcc=[], add_default_subj_pref=True):
subject = format_email_subject(subj, settings.EMAIL_SUBJECT_PREFIX if add_default_subj_pref else '')
msg = EmailMultiAlternatives(
subject,
body,
settings.DEFAULT_FROM_EMAIL,
email if isinstance(email, list) else [email],
bcc=bcc if isinstance(bcc, list) else [bcc],
)
msg.send()