From 2a600b8bef9a739e0abf94d63ca83a672beca26d Mon Sep 17 00:00:00 2001 From: Michal Czuba Date: Fri, 20 Nov 2020 12:31:36 +0100 Subject: [PATCH] Default attachments - added absolute url support --- emailtemplates/email.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/emailtemplates/email.py b/emailtemplates/email.py index 33c14d2..9955130 100644 --- a/emailtemplates/email.py +++ b/emailtemplates/email.py @@ -11,6 +11,8 @@ from .models import now, EmailTemplate from .registry import email_templates +import re +from urllib.parse import urljoin logger = logging.getLogger(__name__) @@ -26,7 +28,7 @@ class EmailFromTemplate(object): Site Admins should be familiar with Django Template System. """ - def __init__(self, name="", from_email=settings.DEFAULT_FROM_EMAIL, + def __init__(self, name="", from_email=settings.DEFAULT_FROM_EMAIL, base_url="", language=settings.LANGUAGE_CODE, subject="", template_class=EmailTemplate, registry_validation=True, template_object=None): """ @@ -49,6 +51,7 @@ def __init__(self, name="", from_email=settings.DEFAULT_FROM_EMAIL, self.subject = subject self.language = language self.name = name + self.base_url = base_url or getattr(settings, "BASE_URL", "") self.template = None self.compiled_template = None # for storing compiled template @@ -79,6 +82,15 @@ def __get_template_from_file(self): else: self._template_source = 'filesystem' + def build_absolute_uri(self, url: str): + """ + Builds an absolute URI. + """ + absolute_http_url_re = re.compile(r"^https?://", re.I) + if absolute_http_url_re.match(url): + return url + return urljoin(self.base_url, url) + def get_template_object(self): if self.template_object: return self.template_object @@ -170,7 +182,9 @@ def get_default_attachments(self, as_links=False): for attachment in tmp.attachments.filter(send_as_link=as_links): if as_links: - attachments.append(attachment.attachment_file.url) + attachments.append( + (attachment.get_name(), self.build_absolute_uri(attachment.attachment_file.url)) + ) else: attachments.append( (os.path.basename(attachment.attachment_file.name), attachment.attachment_file.read())