2015-04-02 16:14:55 +00:00
|
|
|
from urllib.parse import urlparse
|
2014-05-08 16:59:35 +00:00
|
|
|
|
|
|
|
from django.core.mail import EmailMultiAlternatives
|
|
|
|
from django.template.loader import render_to_string
|
|
|
|
from django.template import Context
|
|
|
|
|
|
|
|
|
2015-05-28 10:55:48 +00:00
|
|
|
def render_email_template(template, context):
|
2014-05-08 16:59:35 +00:00
|
|
|
"""
|
|
|
|
Renders an email template with this format:
|
|
|
|
{% if subject %}Subject{% endif %}
|
|
|
|
{% if message %}Email body{% endif %}
|
2021-05-20 12:08:09 +00:00
|
|
|
|
|
|
|
context must be a dict
|
2014-05-08 16:59:35 +00:00
|
|
|
"""
|
|
|
|
if not 'site' in context:
|
|
|
|
from orchestra import settings
|
2015-04-28 15:23:57 +00:00
|
|
|
url = urlparse(settings.ORCHESTRA_SITE_URL)
|
2014-05-08 16:59:35 +00:00
|
|
|
context['site'] = {
|
2015-04-05 22:34:47 +00:00
|
|
|
'name': settings.ORCHESTRA_SITE_NAME,
|
2014-05-08 16:59:35 +00:00
|
|
|
'scheme': url.scheme,
|
|
|
|
'domain': url.netloc,
|
|
|
|
}
|
2017-04-03 17:06:06 +00:00
|
|
|
context['email_part'] = 'subject'
|
|
|
|
subject = render_to_string(template, context).strip()
|
|
|
|
context['email_part'] = 'message'
|
|
|
|
message = render_to_string(template, context).strip()
|
2015-05-28 10:55:48 +00:00
|
|
|
return subject, message
|
|
|
|
|
|
|
|
|
|
|
|
def send_email_template(template, context, to, email_from=None, html=None, attachments=[]):
|
2015-05-30 14:44:05 +00:00
|
|
|
if isinstance(to, str):
|
|
|
|
to = [to]
|
2015-05-28 10:55:48 +00:00
|
|
|
subject, message = render_email_template(template, context)
|
2014-09-04 15:55:43 +00:00
|
|
|
msg = EmailMultiAlternatives(subject, message, email_from, to, attachments=attachments)
|
2014-05-08 16:59:35 +00:00
|
|
|
if html:
|
2015-05-28 10:55:48 +00:00
|
|
|
subject, html_message = render_email_template(html, context)
|
2014-05-08 16:59:35 +00:00
|
|
|
msg.attach_alternative(html_message, "text/html")
|
|
|
|
msg.send()
|