Send a real plain-text version with every HTML email
An app I work on sends the usual transactional email: sign-in links with a six digit code, invitations, receipts. The HTML versions looked fine. Then I opened the raw source of one and found the plain-text part. Every message had the same one line:
This message is best viewed in an email client that supports HTML.
That line is worse than nothing. If a reader actually lands on the plain-text part, the one thing they need (the code, the link) is not there. So I replaced it with a real text version, generated from the HTML the app was already building.
Who actually reads the plain-text part
More people and programs than you would guess:
- Text-only and minimal clients. Some people read mail in a terminal, on a watch, or with HTML turned off for privacy. They get the text part.
- Screen readers and previews. Notification previews and some assistive setups lean on the text part because it has no layout to untangle.
- Spam filters. An HTML body paired with a text part that has nothing in common with it looks a little like what spammers send. A text part that matches the HTML is a small but free signal that the message is legitimate.
For a sign-in email, a reader who sees only the text part should still be able to sign in. That became my test of done.
The approach
I did not want to write every email twice. Hand-written text versions drift from the HTML the first time someone edits a template and forgets the other half. Instead, one function turns the finished HTML into text right before sending, so the two parts always come from the same source.
The rules I settled on:
- Block elements (paragraphs, headings, tables) become blank-line breaks. Table rows and list items become single line breaks, so a receipt still reads as “Gift $50.00” on its own line.
- Every link becomes
label: URL. A button that says “Sign in” is useless as text unless the URL comes with it. - If the link text already is the URL, print it once, not
https://x/give: https://x/give. mailto:links show the address, and#anchors just show their label.- Skip
style,script, andheadcontent completely. - Decode entities, so
&in a query string comes back as a working&.
Python’s standard library has an HTML parser that is plenty for this. Email HTML is usually simple and machine generated, so I did not need a full browser-grade library.
import re
from html.parser import HTMLParser
class TextPart(HTMLParser):
BLOCK = {"p", "div", "h1", "h2", "h3", "table", "ul", "ol"}
LINE = {"tr", "li", "br"}
SKIP = {"style", "script", "head", "title"}
def __init__(self):
super().__init__(convert_charrefs=True) # decodes & and friends
self.out, self.skip = [], 0
self.href, self.link = None, []
def emit(self, s):
(self.link if self.href is not None else self.out).append(s)
def handle_starttag(self, tag, attrs):
if tag in self.SKIP:
self.skip += 1
elif tag in self.BLOCK:
self.out.append("\n\n")
elif tag in self.LINE:
self.emit("\n")
elif tag == "td":
self.emit(" ")
elif tag == "a":
self.href = (dict(attrs).get("href") or "").strip()
self.link = []
def handle_endtag(self, tag):
if tag in self.SKIP:
self.skip = max(0, self.skip - 1)
elif tag in self.BLOCK:
self.out.append("\n\n")
elif tag == "a" and self.href is not None:
label = " ".join("".join(self.link).split())
href, self.href = self.href, None
if href.startswith("mailto:"):
href = href[7:].split("?")[0]
if not href or href.startswith("#") or href in label:
self.out.append(label)
elif not label:
self.out.append(href)
else:
self.out.append(f"{label}: {href}")
def handle_data(self, data):
if not self.skip:
self.emit(data)
def html_to_text(html: str) -> str:
p = TextPart()
p.feed(html)
p.close()
lines = [" ".join(line.split()) for line in "".join(p.out).split("\n")]
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip() + "\n"
Then the sender computes the text once and hands both parts to whichever transport is in use.
With the standard library’s EmailMessage, the text goes in first and the HTML is added as
the alternative, which is the order clients expect:
msg.set_content(html_to_text(html))
msg.add_alternative(html, subtype="html")
For an HTTP email API, it is usually one more field in the payload, often named text.
Testing it
The tests check behavior a reader would notice, not the exact whitespace:
- The sign-in email’s text contains the code, the full sign-in URL with
&decoded, and the expiry footnote. - The invitation’s text contains
Accept your invitation: <url>. - A receipt’s table rows each land on their own line.
- No output contains anything that looks like a tag.
- Converting the HTML does not change the HTML that gets sent. The HTML part is compared byte for byte against the input.
I also wrote one test per transport. The app can send through SMTP, through an HTTP email API,
or through a managed service. For SMTP, the test captures the message and reads back the
text/plain body. For the HTTP API, it captures the JSON payload. For the managed service,
whose API had no documented plain-text field, the test asserts the payload is exactly what it
was before. That last one matters. It records a deliberate choice, so a future change cannot
quietly start sending a field the service might reject.
Finally, the existing safety check on outgoing email still runs before conversion. If a message is blocked, the test confirms the converter never ran and nothing was sent.
Tradeoffs
- Generated text is never as nice as hand-written text. Layout tricks, images used as words, and fancy spacing do not survive. For transactional email that is fine. For a carefully designed newsletter you might still want a written version.
- A small parser has limits. It handles the HTML your own templates produce. If you are converting arbitrary HTML from users, reach for a dedicated library.
- Long URLs make long lines. Some clients wrap them badly. I left them whole, because a link broken across lines is a link that does not work.
- One provider stayed the same. I could have guessed at an undocumented field. I chose to leave it alone and pin that decision with a test instead.
The takeaway
If you send HTML email, the plain-text part is not a formality. Generate it from the same HTML so it never drifts, make sure every link and code survives the trip, and write a test that says “a reader with only the text can still finish the task.” For a sign-in email, that is the whole job.