Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stages/email: fix issue when sending emails to users with same display as email #8850

Merged
merged 1 commit into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion authentik/core/api/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,7 +605,7 @@ def recovery_email(self, request: Request, pk: int) -> Response:
email_stage: EmailStage = stages.first()
message = TemplateEmailMessage(
subject=_(email_stage.subject),
to=[for_user.email],
to=[(for_user.name, for_user.email)],
template_name=email_stage.template,
language=for_user.locale(request),
template_context={
Expand Down
2 changes: 1 addition & 1 deletion authentik/events/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ def send_email(self, notification: "Notification") -> list[str]:
}
mail = TemplateEmailMessage(
subject=subject_prefix + context["title"],
to=[f"{notification.user.name} <{notification.user.email}>"],
to=[(notification.user.name, notification.user.email)],
language=notification.user.locale(),
template_name="email/event_notification.html",
template_context=context,
Expand Down
2 changes: 1 addition & 1 deletion authentik/stages/email/management/commands/test_email.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def handle_per_tenant(self, *args, **options):
delete_stage = True
message = TemplateEmailMessage(
subject="authentik Test-Email",
to=[options["to"]],
to=[("", options["to"])],
template_name="email/setup.html",
template_context={},
)
Expand Down
2 changes: 1 addition & 1 deletion authentik/stages/email/stage.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def send_email(self):
try:
message = TemplateEmailMessage(
subject=_(current_stage.subject),
to=[f"{pending_user.name} <{email}>"],
to=[(pending_user.name, email)],
language=pending_user.locale(self.request),
template_name=current_stage.template,
template_context={
Expand Down
1 change: 1 addition & 0 deletions authentik/stages/email/tests/test_sending.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def test_pending_user(self):
session = self.client.session
session[SESSION_KEY_PLAN] = plan
session.save()
Event.objects.filter(action=EventAction.EMAIL_SENT).delete()

url = reverse("authentik_api:flow-executor", kwargs={"flow_slug": self.flow.slug})
with patch(
Expand Down
11 changes: 11 additions & 0 deletions authentik/stages/email/tests/test_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from django.conf import settings
from django.core.mail.backends.locmem import EmailBackend
from django.core.mail.message import sanitize_address
from django.urls import reverse

from authentik.core.tests.utils import create_test_admin_user, create_test_flow
Expand All @@ -19,6 +20,7 @@
from authentik.flows.tests import FlowTestCase
from authentik.flows.views.executor import SESSION_KEY_PLAN
from authentik.stages.email.models import EmailStage, get_template_choices
from authentik.stages.email.utils import TemplateEmailMessage


def get_templates_setting(temp_dir: str) -> dict[str, Any]:
Expand Down Expand Up @@ -89,3 +91,12 @@ def test_custom_template_invalid_syntax(self):
event.context["message"], "Exception occurred while rendering E-mail template"
)
self.assertEqual(event.context["template"], "invalid.html")

def test_template_address(self):
"""Test addresses are correctly parsed"""
message = TemplateEmailMessage(to=[("foo@bar.baz", "foo@bar.baz")])
[sanitize_address(addr, "utf-8") for addr in message.recipients()]
self.assertEqual(message.recipients(), ["foo@bar.baz"])
message = TemplateEmailMessage(to=[("some-name", "foo@bar.baz")])
[sanitize_address(addr, "utf-8") for addr in message.recipients()]
self.assertEqual(message.recipients(), ["some-name <foo@bar.baz>"])
15 changes: 13 additions & 2 deletions authentik/stages/email/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,19 @@ def logo_data() -> MIMEImage:
class TemplateEmailMessage(EmailMultiAlternatives):
"""Wrapper around EmailMultiAlternatives with integrated template rendering"""

def __init__(self, template_name=None, template_context=None, language="", **kwargs):
super().__init__(**kwargs)
def __init__(
self, to: list[tuple[str]], template_name=None, template_context=None, language="", **kwargs
):
sanitized_to = []
# Ensure that all recipients are valid
for recipient_name, recipient_email in to:
if recipient_name == recipient_email:
sanitized_to.append(recipient_email)
else:
sanitized_to.append(f"{recipient_name} <{recipient_email}>")
super().__init__(to=sanitized_to, **kwargs)
if not template_name:
return
with translation.override(language):
html_content = render_to_string(template_name, template_context)
try:
Expand Down