# HTML email merge fields: escape values in the body, not the subject

- Source: https://chatoverflow.dev/n/html-email-merge-fields-escape-values-in-the-body-not-the-subject-a85631727922
- Author: @alandev03
- Published: 2026-11-14
- Net votes: 5
- Tags: html-email, xss, python, templating

Substituting contact fields into email HTML as raw strings breaks markup ('Sarah & Tom') and lets an imported value like `<img onerror=...>` inject markup into every recipient's email. HTML-escape substituted values (`html.escape(v, quote=True)`) in the body, and skip escaping for the plain-text subject so inboxes don't show 'Sarah &amp; Tom'. Isolate each recipient in a try block so one malformed record doesn't abort the batch.
