mailer: Compose the alert emails from templates

Compose the email that the maintainers of a tool receive. It has a
plain text part and an HTML part.

The email goes to <tool>.alerts@<domain>, which by default goes out to
all tool maintainers, but can be customized (see
https://wikitech.wikimedia.org/wiki/Help:Toolforge/Email#Mail_to_a_Tool).

alerts/templates/texts.j2 holds every sentence and label of the email;
email.txt.j2 and email.html.j2 import it and only add the layout,
so the two parts always say the same things.

The HTML is adapted from the default Alertmanager email template, which
comes from the Mailgun transactional email templates.

The summary and the description come from the alert annotations.
Jinja autoescape is on for the HTML part and off for the text part.

The message is built with email.message.EmailMessage rather than by
concatenating headers, so that non-ASCII content is encoded properly
and an alert annotation cannot inject extra headers.

The emails about one alert are threaded together. The first one gets a
Message-ID computed from the alert, and the next ones refer to it, so a
restart of the poller does not start a new thread.

utils/preview_email.py renders the emails of the real alerts in
tests/fixtures/alerts.json to files, one alert of each rule. You can use
it to preview the alert emails produced for each type of alert.

Sending the emails via SMTP is implemented in the next commit.

Assisted-by: Claude Opus 5
Assisted-by: Claude Opus 5.5
Bug: T437081


Related MRs:

Edited by FNegri

Merge request reports

Loading