64 lines
2.2 KiB
Python
64 lines
2.2 KiB
Python
# -*- coding: utf-8 -*-
|
|
import logging
|
|
from django.apps import apps
|
|
from django.core.exceptions import ImproperlyConfigured
|
|
from django.core.mail import EmailMessage
|
|
from django.template.loader import get_template
|
|
|
|
app_config = apps.get_containing_app_config(__package__)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class AbstractMail: # pylint: disable=too-few-public-methods
|
|
_subject = ''
|
|
_template_name = None
|
|
|
|
def _get_sender(self):
|
|
return app_config.settings.email_sender
|
|
|
|
def _get_subject(self, subject_fmt=None, **kwargs):
|
|
if subject_fmt is None:
|
|
subject_fmt = self._subject
|
|
if app_config.settings.email_subject_prefix:
|
|
subject_fmt = '%s %s' % (app_config.settings.email_subject_prefix, subject_fmt)
|
|
subject = subject_fmt.format(**kwargs)
|
|
return subject
|
|
|
|
def _get_template(self):
|
|
if not self._template_name:
|
|
raise ImproperlyConfigured('%s._template_name ist not set.' % self.__class__.__name__)
|
|
return get_template(self._template_name, using='PLAINTEXT')
|
|
|
|
def _get_context_data(self, extra_context=None):
|
|
context = {
|
|
'base_url': app_config.settings.email_base_url,
|
|
}
|
|
if extra_context:
|
|
context.update(extra_context)
|
|
return context
|
|
|
|
def _get_body(self, context=None):
|
|
template = self._get_template()
|
|
context = self._get_context_data(extra_context=context)
|
|
return template.render(context)
|
|
|
|
def _get_recipients(self):
|
|
raise NotImplementedError()
|
|
|
|
def _get_reply_to(self):
|
|
return None
|
|
|
|
def send(self, fail_silently=False):
|
|
subject = self._get_subject()
|
|
body = self._get_body()
|
|
sender = self._get_sender()
|
|
recipients = self._get_recipients()
|
|
reply_to = self._get_reply_to()
|
|
|
|
email = EmailMessage(subject=subject, body=body, from_email=sender, to=recipients, reply_to=reply_to)
|
|
if fail_silently:
|
|
logger.info('Fake sending %s to %s', self.__class__.__name__, recipients)
|
|
else:
|
|
logger.info('Send %s to %s', self.__class__.__name__, recipients)
|
|
email.send(fail_silently=fail_silently)
|