Skip to content

Commit

Permalink
Default attachments - added absolute url support
Browse files Browse the repository at this point in the history
  • Loading branch information
Michal Czuba committed Nov 20, 2020
1 parent 9b7d97f commit 2a600b8
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions emailtemplates/email.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand All @@ -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):
"""
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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())
Expand Down

0 comments on commit 2a600b8

Please sign in to comment.