DEV Community

linkbruno.com
linkbruno.com

Posted on

How to check every link in your HTML email templates before they're sent (a Python script for CI)

Scheduled broken-link and redirect checks that tell you the moment a link breaks — linkbruno.com

Websites get second chances. You find a broken link, fix it, deploy, and everyone who visits from then on sees the fix.

Emails don't. Once a password reset, a receipt, an onboarding sequence or a newsletter goes out, every link in it is fixed in place, in thousands of inboxes, for years. People search their mail for "invoice" in 2028 and click the link you wrote in 2026.

So it's worth checking email links before they're sent, ideally on every change to a template. Here's a small Python script that does that.

What actually breaks in email links

From experience, in roughly this order:

  1. Unrendered placeholders. https://app.example.com/invite/{{token}} or href="%%unsubscribe%%" because a variable name changed or a merge tag isn't supported by the sending tool.
  2. Staging or localhost hosts. A template tested locally with http://localhost:3000 or https://staging.example.com, and the base URL never switched.
  3. Paths that changed. The app renamed /settings/billing to /account/billing, and the template still has the old path.
  4. Broken images. Logo URLs pointing at an asset path that was moved or a hashed file from an old build.
  5. Help-centre links to articles that were reorganised.

A plain link checker can find 3 to 5. The first two need checks of their own.

The script

This assumes Jinja2 templates in a templates/email/ folder and a JSON file of sample data per template. Adjust the rendering part for whatever your app uses (Handlebars, MJML output, Django templates); the checking part stays the same.

pip install jinja2 requests
Enter fullscreen mode Exit fullscreen mode
#!/usr/bin/env python3
"""Render email templates with sample data and check every link and image."""
import json, re, sys, pathlib
from html.parser import HTMLParser
import requests
from jinja2 import Environment, FileSystemLoader, StrictUndefined

TEMPLATES = pathlib.Path("templates/email")
SAMPLES = pathlib.Path("templates/email/samples")
BAD_HOSTS = ("localhost", "127.0.0.1", "staging.", "dev.", ".local", "ngrok")
PLACEHOLDER = re.compile(r"\{\{|\}\}|%%|\*\|")   # Jinja, %%tag%%, *|MERGE|*

class Links(HTMLParser):
    def __init__(self):
        super().__init__(); self.urls = []
    def handle_starttag(self, tag, attrs):
        a = dict(attrs)
        if tag == "a" and a.get("href"): self.urls.append(("href", a["href"]))
        if tag == "img" and a.get("src"): self.urls.append(("img", a["src"]))

env = Environment(loader=FileSystemLoader(TEMPLATES), undefined=StrictUndefined)
session = requests.Session(); cache = {}

def check(url):
    if url not in cache:
        try:
            r = session.get(url, allow_redirects=True, timeout=15, stream=True)
            cache[url] = r.status_code
        except requests.RequestException as e:
            cache[url] = type(e).__name__
    return cache[url]

problems = 0
for tpl in sorted(TEMPLATES.glob("*.html")):
    sample = SAMPLES / (tpl.stem + ".json")
    data = json.loads(sample.read_text()) if sample.exists() else {}
    try:
        html = env.get_template(tpl.name).render(**data)
    except Exception as e:
        print(f"{tpl.name}: RENDER ERROR {e}"); problems += 1; continue
    p = Links(); p.feed(html)
    for kind, url in p.urls:
        if url.startswith(("mailto:", "tel:", "#")):
            continue
        if PLACEHOLDER.search(url):
            print(f"{tpl.name}: [{kind}] unrendered placeholder: {url}"); problems += 1; continue
        if any(h in url for h in BAD_HOSTS) or url.startswith("http://"):
            print(f"{tpl.name}: [{kind}] bad host or http: {url}"); problems += 1; continue
        status = check(url)
        if not (isinstance(status, int) and status < 400):
            print(f"{tpl.name}: [{kind}] {status}: {url}"); problems += 1

print(f"{problems} problem(s)")
sys.exit(1 if problems else 0)
Enter fullscreen mode Exit fullscreen mode

A sample data file, templates/email/samples/receipt.json:

{ "base_url": "https://app.example.com", "invoice_id": "in_test_123", "customer_name": "Sam" }
Enter fullscreen mode Exit fullscreen mode

Why it's built this way

Render first, then check. The links that break in email are mostly built from variables. Checking the raw template finds {{ base_url }}/account, which tells you nothing. Rendering with realistic sample data gives you the URL a customer would actually get.

StrictUndefined. By default Jinja2 renders a missing variable as an empty string, producing links like https:///account/billing. Strict mode turns that into a render error, which is what you want in CI.

Placeholder detection after rendering. If {{ or %% survives rendering, it's either a typo or a merge tag your sending platform is supposed to replace. The script flags both; add an allow-list for the tags your provider really does support (like its unsubscribe tag) so they don't fail the build.

Images count. A broken logo makes an email look like phishing. Checking img src is cheap.

GET with stream=True. Some servers don't handle HEAD properly; streaming avoids downloading large files.

Pre-send checks catch what's broken today; the links in emails you already sent can break next month. linkbruno.com keeps checking the URLs your emails point to on a schedule, so a renamed help article or moved billing page is caught before customers start clicking it from old mail.

Links that need special handling

  • Signed or expiring links (password resets, magic logins, "view receipt" links with a token). The sample token won't be valid, so these will fail or redirect to a login page. Check that they reach the right page (a 200 on the login or "link expired" screen) rather than expecting success.
  • Click-tracking redirects. Many email providers rewrite links through a tracking domain at send time. Your template check can't see those, so send one real test email to a seed inbox and check the tracked links too, including that the tracking domain's certificate is valid.
  • Unsubscribe links are required by law in many places and by the big mailbox providers for bulk senders. Make sure at least one test checks it resolves.

Running it in CI

Run the script on every pull request that touches templates/email/ or the routes those templates link to. A route rename that breaks an email link fails the build in the same PR that caused it, which is the cheapest possible place to fix it.

Then add the destination URLs to whatever recurring link check you run, linkbruno.com or your own, because the pages emails point to keep changing long after the email is sent.

Related reading

Do you test the links in your transactional emails at all? I'm curious how many teams have found a {{ in a real customer's inbox.

Top comments (0)