Skip to content

Commit

Permalink
fix(email): use a custom engine for plaintext emails
Browse files Browse the repository at this point in the history
  • Loading branch information
keeakita committed Aug 22, 2024
1 parent a43fdb8 commit f48a3f3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
10 changes: 9 additions & 1 deletion src/sentry/utils/email/message_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

import lxml.html
import toronado
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.template.engine import Engine
from django.utils.encoding import force_str

from sentry import options
Expand Down Expand Up @@ -132,8 +134,14 @@ def __render_html_body(self) -> str | None:
return inline_css(html_body)

def __render_text_body(self) -> str:
# Create a clone of the default Django templater with autoescape disabled.
# TODO: cache this?
params = settings.TEMPLATES[0].copy()
params["OPTIONS"]["autoescape"] = False
engine = Engine(params["DIRS"], params["APP_DIRS"], **params["OPTIONS"])

if self.template:
body: str = render_to_string(self.template, self.context)
body: str = render_to_string(self.template, self.context, engine=engine)
return body
return self._txt_body

Expand Down
11 changes: 9 additions & 2 deletions src/sentry/web/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
from typing import Any

from django.http import HttpRequest, HttpResponse
from django.template import loader
from django.template import Context, loader
from django.template.engine import Engine
from django.utils import timezone

from sentry.utils.dates import AVAILABLE_TIMEZONES
Expand All @@ -17,6 +18,7 @@ def render_to_string(
template: Sequence[str] | str,
context: Mapping[str, Any] | None = None,
request: HttpRequest | None = None,
engine: Engine | None = None,
) -> str:
if context is None:
context = dict()
Expand All @@ -26,7 +28,12 @@ def render_to_string(
if "timezone" in context and context["timezone"] in AVAILABLE_TIMEZONES:
timezone.activate(context["timezone"])

rendered = loader.render_to_string(template, context=context, request=request)
if engine is None:
rendered = loader.render_to_string(template, context=context, request=request)
else:
template_compiled = engine.get_template(template)
rendered = template_compiled.render(Context(context, autoescape=engine.autoescape))

timezone.deactivate()

return rendered
Expand Down

0 comments on commit f48a3f3

Please sign in to comment.