2016-08-21 05:28:22 +00:00
|
|
|
import os
|
|
|
|
|
2012-07-12 05:20:55 +00:00
|
|
|
from django.conf import settings
|
|
|
|
from django.core.mail import EmailMultiAlternatives
|
|
|
|
from django.template.loader import render_to_string
|
|
|
|
from django.utils.html import strip_tags
|
|
|
|
|
|
|
|
from django.contrib.sites.models import Site
|
|
|
|
|
|
|
|
|
2016-08-21 05:31:09 +00:00
|
|
|
class Sender(object):
|
2020-11-22 12:21:54 +00:00
|
|
|
''' Class for sending e-mails under a template prefix. '''
|
2016-08-21 05:28:22 +00:00
|
|
|
|
2016-08-21 05:31:09 +00:00
|
|
|
def __init__(self, template_prefix):
|
|
|
|
self.template_prefix = template_prefix
|
|
|
|
|
|
|
|
def send_email(self, to, kind, **kwargs):
|
2016-08-21 05:28:22 +00:00
|
|
|
''' Sends an e-mail to the given address.
|
|
|
|
|
|
|
|
to: The address
|
|
|
|
kind: the ID for an e-mail kind; it should point to a subdirectory of
|
2016-08-21 05:31:09 +00:00
|
|
|
self.template_prefix containing subject.txt and message.html, which
|
2016-08-21 05:28:22 +00:00
|
|
|
are django templates for the subject and HTML message respectively.
|
|
|
|
|
|
|
|
context: a context for rendering the e-mail.
|
|
|
|
|
2016-08-21 05:31:09 +00:00
|
|
|
'''
|
2016-08-21 05:28:22 +00:00
|
|
|
|
2016-08-21 05:31:09 +00:00
|
|
|
return __send_email__(self.template_prefix, to, kind, **kwargs)
|
2016-08-21 05:28:22 +00:00
|
|
|
|
|
|
|
|
2016-08-21 05:31:09 +00:00
|
|
|
send_email = Sender("symposion/emails").send_email
|
2016-08-21 05:28:22 +00:00
|
|
|
|
|
|
|
|
|
|
|
def __send_email__(template_prefix, to, kind, **kwargs):
|
2014-07-30 18:19:26 +00:00
|
|
|
|
2012-07-12 05:20:55 +00:00
|
|
|
current_site = Site.objects.get_current()
|
2014-07-30 18:19:26 +00:00
|
|
|
|
2012-07-12 05:20:55 +00:00
|
|
|
ctx = {
|
|
|
|
"current_site": current_site,
|
|
|
|
"STATIC_URL": settings.STATIC_URL,
|
|
|
|
}
|
|
|
|
ctx.update(kwargs.get("context", {}))
|
2016-08-21 05:28:22 +00:00
|
|
|
subject_template = os.path.join(template_prefix, "%s/subject.txt" % kind)
|
|
|
|
message_template = os.path.join(template_prefix, "%s/message.html" % kind)
|
2012-07-12 05:20:55 +00:00
|
|
|
subject = "[%s] %s" % (
|
|
|
|
current_site.name,
|
2016-08-21 05:28:22 +00:00
|
|
|
render_to_string(subject_template, ctx).strip()
|
2012-07-12 05:20:55 +00:00
|
|
|
)
|
2014-07-30 18:19:26 +00:00
|
|
|
|
2016-08-21 05:28:22 +00:00
|
|
|
message_html = render_to_string(message_template, ctx)
|
2012-07-12 05:20:55 +00:00
|
|
|
message_plaintext = strip_tags(message_html)
|
2014-07-30 18:19:26 +00:00
|
|
|
|
2012-07-12 05:20:55 +00:00
|
|
|
from_email = settings.DEFAULT_FROM_EMAIL
|
2014-07-30 18:19:26 +00:00
|
|
|
|
2016-09-07 02:01:34 +00:00
|
|
|
email = EmailMultiAlternatives(subject, message_plaintext, from_email, to)
|
2012-07-12 05:20:55 +00:00
|
|
|
email.attach_alternative(message_html, "text/html")
|
|
|
|
email.send()
|