authentik.stages.email.utils

email utils

 1"""email utils"""
 2
 3from email.mime.image import MIMEImage
 4from functools import lru_cache
 5from pathlib import Path
 6
 7from django.conf import settings
 8from django.core.mail import EmailMultiAlternatives
 9from django.core.mail.message import sanitize_address
10from django.template.exceptions import TemplateDoesNotExist
11from django.template.loader import render_to_string
12from django.utils import translation
13from django.utils.functional import Promise
14
15
16@lru_cache
17def logo_data() -> MIMEImage:
18    """Get logo as MIME Image for emails"""
19    path = Path("web/dist/assets/icons/icon_left_brand.png")
20    # When running tests, assets might not exist, so fallback to a different icon
21    if settings.TEST:
22        path = Path("web/authentik/sources/saml/light.png")
23    with open(path, "rb") as _logo_file:
24        logo = MIMEImage(_logo_file.read())
25    logo.add_header("Content-ID", "<logo>")
26    logo.add_header("Content-Disposition", "inline", filename="logo.png")
27    return logo
28
29
30def _sanitize_recipients(recipients: list[tuple[str, str]]) -> list[str]:
31    """Sanitize a list of (name, email) tuples into valid email addresses."""
32    sanitized = []
33    for recipient_name, recipient_email in recipients:
34        # Remove any newline characters from name and email before sanitizing
35        clean_name = recipient_name.replace("\n", " ").replace("\r", " ") if recipient_name else ""
36        clean_email = recipient_email.replace("\n", "").replace("\r", "") if recipient_email else ""
37        sanitized.append(sanitize_address((clean_name, clean_email), "utf-8"))
38    return sanitized
39
40
41class TemplateEmailMessage(EmailMultiAlternatives):
42    """Wrapper around EmailMultiAlternatives with integrated template rendering"""
43
44    def __init__(
45        self,
46        to: list[tuple[str, str]],
47        cc: list[tuple[str, str]] | None = None,
48        bcc: list[tuple[str, str]] | None = None,
49        template_name=None,
50        template_context=None,
51        language="",
52        **kwargs,
53    ):
54        sanitized_to = _sanitize_recipients(to)
55        sanitized_cc = _sanitize_recipients(cc) if cc else None
56        sanitized_bcc = _sanitize_recipients(bcc) if bcc else None
57        super().__init__(to=sanitized_to, cc=sanitized_cc, bcc=sanitized_bcc, **kwargs)
58        if isinstance(self.subject, Promise):
59            with translation.override(language):
60                self.subject = str(self.subject)
61        if not template_name:
62            return
63        with translation.override(language):
64            html_content = render_to_string(template_name, template_context)
65            try:
66                text_content = render_to_string(
67                    template_name.replace("html", "txt"), template_context
68                )
69                self.body = text_content
70            except TemplateDoesNotExist:
71                pass
72        self.mixed_subtype = "related"
73        self.attach_alternative(html_content, "text/html")
@lru_cache
def logo_data() -> email.mime.image.MIMEImage:
17@lru_cache
18def logo_data() -> MIMEImage:
19    """Get logo as MIME Image for emails"""
20    path = Path("web/dist/assets/icons/icon_left_brand.png")
21    # When running tests, assets might not exist, so fallback to a different icon
22    if settings.TEST:
23        path = Path("web/authentik/sources/saml/light.png")
24    with open(path, "rb") as _logo_file:
25        logo = MIMEImage(_logo_file.read())
26    logo.add_header("Content-ID", "<logo>")
27    logo.add_header("Content-Disposition", "inline", filename="logo.png")
28    return logo

Get logo as MIME Image for emails

class TemplateEmailMessage(django.core.mail.message.EmailMultiAlternatives):
42class TemplateEmailMessage(EmailMultiAlternatives):
43    """Wrapper around EmailMultiAlternatives with integrated template rendering"""
44
45    def __init__(
46        self,
47        to: list[tuple[str, str]],
48        cc: list[tuple[str, str]] | None = None,
49        bcc: list[tuple[str, str]] | None = None,
50        template_name=None,
51        template_context=None,
52        language="",
53        **kwargs,
54    ):
55        sanitized_to = _sanitize_recipients(to)
56        sanitized_cc = _sanitize_recipients(cc) if cc else None
57        sanitized_bcc = _sanitize_recipients(bcc) if bcc else None
58        super().__init__(to=sanitized_to, cc=sanitized_cc, bcc=sanitized_bcc, **kwargs)
59        if isinstance(self.subject, Promise):
60            with translation.override(language):
61                self.subject = str(self.subject)
62        if not template_name:
63            return
64        with translation.override(language):
65            html_content = render_to_string(template_name, template_context)
66            try:
67                text_content = render_to_string(
68                    template_name.replace("html", "txt"), template_context
69                )
70                self.body = text_content
71            except TemplateDoesNotExist:
72                pass
73        self.mixed_subtype = "related"
74        self.attach_alternative(html_content, "text/html")

Wrapper around EmailMultiAlternatives with integrated template rendering

TemplateEmailMessage( to: list[tuple[str, str]], cc: list[tuple[str, str]] | None = None, bcc: list[tuple[str, str]] | None = None, template_name=None, template_context=None, language='', **kwargs)
45    def __init__(
46        self,
47        to: list[tuple[str, str]],
48        cc: list[tuple[str, str]] | None = None,
49        bcc: list[tuple[str, str]] | None = None,
50        template_name=None,
51        template_context=None,
52        language="",
53        **kwargs,
54    ):
55        sanitized_to = _sanitize_recipients(to)
56        sanitized_cc = _sanitize_recipients(cc) if cc else None
57        sanitized_bcc = _sanitize_recipients(bcc) if bcc else None
58        super().__init__(to=sanitized_to, cc=sanitized_cc, bcc=sanitized_bcc, **kwargs)
59        if isinstance(self.subject, Promise):
60            with translation.override(language):
61                self.subject = str(self.subject)
62        if not template_name:
63            return
64        with translation.override(language):
65            html_content = render_to_string(template_name, template_context)
66            try:
67                text_content = render_to_string(
68                    template_name.replace("html", "txt"), template_context
69                )
70                self.body = text_content
71            except TemplateDoesNotExist:
72                pass
73        self.mixed_subtype = "related"
74        self.attach_alternative(html_content, "text/html")

Initialize a single email message (which can be sent to multiple recipients).

mixed_subtype = 'mixed'