Coverage for app/backend/src/couchers/email/rendering.py: 95%
117 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-27 22:43 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-27 22:43 +0000
1"""
2Renders blocks-based emails to HTML or plaintext emails for a locale.
3"""
5import re
6from dataclasses import asdict, dataclass
7from email.headerregistry import Address
8from functools import cache
9from pathlib import Path
10from typing import Any
12from markupsafe import Markup
14from couchers.config import config
15from couchers.email.blocks import (
16 ActionBlock,
17 ActionPairBlock,
18 EmailBase,
19 EmailBlock,
20 EmailFooter,
21 ParaBlock,
22 QuoteBlock,
23 UserBlock,
24)
25from couchers.email.locales import get_emails_i18next
26from couchers.email.smtp import embed_html_relative_images
27from couchers.i18n import LocalizationContext
28from couchers.i18n.i18next import SubstitutionDict, full_string_key
29from couchers.markup import html_mailto_link, html_to_plaintext, markdown_to_html
30from couchers.proto.internal import jobs_pb2
31from couchers.templating import Jinja2Template
33template_folder = Path(__file__).parent.parent.parent.parent / "templates" / "v2"
36@dataclass(kw_only=True, slots=True)
37class RenderedEmail:
38 subject: str
39 body_plaintext: str
40 body_html: str
41 html_image_parts: list[jobs_pb2.EmailPart]
44def render_email(
45 email: EmailBase, footer: EmailFooter, loc_context: LocalizationContext, *, embed_images: bool = True
46) -> RenderedEmail:
47 """Renders an EmailBase object to subject and body strings."""
48 subject = email.get_subject_line(loc_context)
49 preview = email.get_preview_line(loc_context)
50 body_blocks = email.get_body_blocks(loc_context)
52 body_plaintext = render_plaintext_body(blocks=body_blocks, footer=footer, loc_context=loc_context)
53 body_html = render_html_body(
54 subject=subject, preview=preview, blocks=body_blocks, footer=footer, loc_context=loc_context
55 )
57 related_parts: list[jobs_pb2.EmailPart] = []
58 if embed_images:
59 content_id_domain = Address(addr_spec=config.NOTIFICATION_EMAIL_ADDRESS).domain
60 body_html, related_parts = embed_html_relative_images(
61 body_html, base_dir=template_folder, content_id_domain=content_id_domain
62 )
64 return RenderedEmail(
65 subject=subject, body_plaintext=body_plaintext, body_html=body_html, html_image_parts=related_parts
66 )
69def render_plaintext_body(*, blocks: list[EmailBlock], footer: EmailFooter, loc_context: LocalizationContext) -> str:
70 """Renders the body of an email as plaintext."""
71 concat: list[str] = []
73 for block_index, block in enumerate(blocks):
74 if block_index > 0:
75 concat.append("\n\n")
77 match block:
78 case ParaBlock():
79 concat.append(_to_plaintext(block.text))
80 case UserBlock():
81 line = loc_context.localize_string(
82 "plaintext_formats.user",
83 i18next=get_emails_i18next(),
84 substitutions={"name": block.info.name, "age": str(block.info.age), "city": block.info.city},
85 )
86 concat.append(line)
87 if block.comment:
88 concat.append("\n")
89 concat.append(_to_plaintext(block.comment))
90 case QuoteBlock():
91 for line in block.text.splitlines():
92 concat.append(f"> {line}")
93 case ActionBlock():
94 concat.append(_plaintext_action_line(block.text, block.target_url, loc_context))
95 case ActionPairBlock(): 95 ↛ 99line 95 didn't jump to line 99 because the pattern on line 95 always matched
96 concat.append(_plaintext_action_line(block.primary_text, block.primary_target_url, loc_context))
97 concat.append("\n")
98 concat.append(_plaintext_action_line(block.secondary_text, block.secondary_target_url, loc_context))
99 case _:
100 raise TypeError(f"Unexpected email block type: {block.__class__}")
102 concat.append("\n\n")
104 footer_template = Jinja2Template(
105 source=(template_folder / "_footer.txt").read_text(encoding="utf8").strip(), html=False
106 )
107 footer_template_args = _get_footer_template_args(footer, loc_context)
108 concat.append(footer_template.render(footer_template_args))
110 return "".join(concat)
113def _plaintext_action_line(text: str, target_url: str, loc_context: LocalizationContext) -> str:
114 return loc_context.localize_string(
115 "plaintext_formats.action",
116 i18next=get_emails_i18next(),
117 substitutions={"text": text, "url": target_url},
118 )
121def _to_plaintext(text: str | Markup) -> str:
122 """
123 Converts any markup in its plaintext equivalent, allowing reuse of translations that have span-level markup
124 like <b> when formatting as plaintext email bodies.
125 """
126 if isinstance(text, Markup): 126 ↛ 129line 126 didn't jump to line 129 because the condition on line 126 was always true
127 return html_to_plaintext(text)
128 else:
129 return text
132def _get_footer_template_args(footer: EmailFooter, loc_context: LocalizationContext) -> dict[str, Any]:
133 i18n = get_emails_i18next()
135 def localize(key: str, substitutions: SubstitutionDict | None = None) -> Markup:
136 key = full_string_key(key, relative_base="generic.footer")
137 return i18n.localize_with_markup(key, loc_context.locale_list, substitutions)
139 args: dict[str, Any] = {
140 "received_because": localize(".received_because"),
141 "contact_support": localize(".contact_support", {"email_link": html_mailto_link("support@couchers.org")}),
142 "copyright_year": footer.copyright_year,
143 "donate_link": localize(".donate_link"),
144 "volunteer_link": localize(".volunteer_link"),
145 "blog_link": localize(".blog_link"),
146 "nonprofit_note": localize(".nonprofit_note"),
147 "is_critical": footer.unsubscribe_info is None,
148 }
150 if unsubscribe_info := footer.unsubscribe_info:
151 # TODO(#7420): Localize "Turn off emails for: " text, avoiding string concatenations.
152 args.update(
153 {
154 "notification_settings_link": localize(".notification_settings_link"),
155 "manage_notifications_url": unsubscribe_info.manage_notifications_url,
156 "do_not_email_link": localize(".do_not_email_link"),
157 "do_not_email_url": unsubscribe_info.do_not_email_url,
158 "topic_action_description": unsubscribe_info.topic_action_link.text,
159 "unsubscribe_topic_action_url": unsubscribe_info.topic_action_link.url,
160 }
161 )
163 if topic_key_link := unsubscribe_info.topic_key_link:
164 args["topic_key_description"] = topic_key_link.text
165 args["unsubscribe_topic_key_url"] = topic_key_link.url
166 else:
167 args["security_email_note"] = localize(".security_email_note")
169 return args
172def render_html_body(
173 *,
174 subject: str,
175 preview: str | None,
176 blocks: list[EmailBlock],
177 footer: EmailFooter,
178 loc_context: LocalizationContext,
179) -> str:
180 """Renders the body of an email as HTML."""
181 return HTMLRenderer.default().render(
182 subject=subject, preview=preview, blocks=blocks, footer=footer, loc_context=loc_context
183 )
186# Matches a begin-block / end-block pair of comments in the html file containing template
187_block_regex = re.compile(
188 r"""
189<!-- begin-block:(?P<name>[\w-]+) -->\s*
190(?P<snippet>[\s\S]*?)
191\s*<!-- end-block:(?P=name) -->
192""".strip(),
193 re.MULTILINE,
194)
197@dataclass
198class HTMLRenderer:
199 """Renders an email as HTML using template snippets for the header, footer and each block."""
201 header_template: Jinja2Template
202 footer_template: Jinja2Template
203 para_block_template: Jinja2Template
204 user_block_template: Jinja2Template
205 quote_block_template: Jinja2Template
206 action_block_template: Jinja2Template
207 action_pair_block_template: Jinja2Template
209 def render(
210 self,
211 *,
212 subject: str,
213 preview: str | None,
214 blocks: list[EmailBlock],
215 footer: EmailFooter,
216 loc_context: LocalizationContext,
217 ) -> str:
218 concats: list[str] = []
220 # Render the header
221 concats.append(
222 self.header_template.render(
223 {
224 "header_subject": subject,
225 "header_preview": preview or "",
226 },
227 )
228 )
230 # Render each block
231 for block in blocks:
232 match block:
233 case ParaBlock():
234 concats.append(self.para_block_template.render(asdict(block)))
235 case UserBlock():
236 concats.append(
237 self.user_block_template.render(
238 {
239 "name": block.info.name,
240 "age": block.info.age,
241 "city": block.info.city,
242 "profile_url": block.info.profile_url,
243 "avatar_url": block.info.avatar_url,
244 "comment": block.comment,
245 },
246 )
247 )
248 case QuoteBlock():
249 args = {"text": Markup(markdown_to_html(block.text)) if block.markdown else block.text}
250 concats.append(self.quote_block_template.render(args))
251 case ActionBlock():
252 concats.append(self.action_block_template.render(asdict(block)))
253 case ActionPairBlock(): 253 ↛ 264line 253 didn't jump to line 264 because the pattern on line 253 always matched
254 concats.append(
255 self.action_pair_block_template.render(
256 {
257 "primary_text": block.primary_text,
258 "primary_url": block.primary_target_url,
259 "secondary_text": block.secondary_text,
260 "secondary_url": block.secondary_target_url,
261 },
262 )
263 )
264 case _:
265 raise TypeError(f"Unexpected email block type: {block.__class__}")
267 # Render the footer
268 footer_template_args = _get_footer_template_args(footer, loc_context)
269 concats.append(self.footer_template.render(footer_template_args))
271 return "\n".join(concats)
273 @cache
274 @staticmethod
275 def default() -> HTMLRenderer:
276 template = (template_folder / "generated_html" / "blocks.html").read_text(encoding="utf8")
277 return HTMLRenderer.from_template(template)
279 @staticmethod
280 def from_template(template: str) -> HTMLRenderer:
281 section_matches = list(_block_regex.finditer(template))
283 header_template = template[: section_matches[0].start()]
284 footer_template = template[section_matches[-1].end() :]
285 block_templates = {match.group("name"): match.group("snippet") for match in section_matches}
287 return HTMLRenderer(
288 header_template=Jinja2Template(source=header_template, html=True),
289 footer_template=Jinja2Template(source=footer_template, html=True),
290 para_block_template=Jinja2Template(source=block_templates["para"], html=True),
291 user_block_template=Jinja2Template(source=block_templates["user"], html=True),
292 quote_block_template=Jinja2Template(source=block_templates["quote"], html=True),
293 action_block_template=Jinja2Template(source=block_templates["action"], html=True),
294 action_pair_block_template=Jinja2Template(source=block_templates["action-pair"], html=True),
295 )