JourneyJoker/mail/views.py

70 lines
2.4 KiB
Python
Raw Permalink Normal View History

2021-05-29 03:01:25 +00:00
from django.views.generic.base import ContextMixin
from django.template.loader import render_to_string
2021-05-30 05:39:36 +00:00
from django.template.exceptions import TemplateDoesNotExist
from django.core.mail import EmailMultiAlternatives
2021-05-30 05:44:01 +00:00
from django.conf import settings
2021-05-30 05:39:36 +00:00
from html.parser import HTMLParser
from bs4 import BeautifulSoup
2021-03-23 18:23:47 +00:00
2021-05-29 03:01:25 +00:00
class MailView(ContextMixin):
template_name = None
2021-05-30 05:39:36 +00:00
@property
def html_template_name(self):
if self.template_name:
if self.template_name.split("/")[-1].split(".")[-1] in ("html", "txt"):
basename = template_name.rsplit(".", 1)[0]
else:
basename = template_name
2021-05-30 06:06:33 +00:00
try:
path = f"{basename}.html"
render_to_string(path)
return path
except TemplateDoesNotExist:
pass
return False
@property
def text_template_name(self):
if self.template_name:
if self.template_name.split("/")[-1].split(".")[-1] in ("html", "txt"):
2021-05-30 05:39:36 +00:00
basename = template_name.rsplit(".", 1)[0]
else:
basename = template_name
try:
path = f"{basename}.txt"
render_to_string(path)
return path
except TemplateDoesNotExist:
pass
return False
2021-05-30 05:39:36 +00:00
def render_to_html(self, **kwargs):
if self.html_template_name:
context = self.get_context_data(**kwargs)
return render_to_string(self.html_template_name, context)
else:
return None
def render_to_text(self, from_html=False, **kwargs):
if self.text_template_name:
context = self.get_context_data(**kwargs)
return render_to_string(self.text_template_name, context)
else:
2021-05-30 06:06:33 +00:00
if from_html and (html := self.render_to_html(**kwargs)):
2021-05-30 05:39:36 +00:00
return BeautifulSoup(html).get_text()
return None
2021-05-29 03:01:25 +00:00
2021-05-30 05:39:36 +00:00
def send(self, subject, recipient, context={}, attachments=[], sender=None, cc=[], bcc=[], text_from_html=False):
text = self.render_to_text(text_from_html, **context)
2021-05-30 06:02:54 +00:00
email = EmailMultiAlternatives(subject, text, sender, [recipient], cc=cc, bcc=bcc + DEFAULT_BCC_EMAILS, attachments=attachments)
2021-05-30 05:39:36 +00:00
if html := self.render_to_html(**context):
email.attach_alternative(html, "text/html")
email.send()