Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(conversations): recover lost links from inbound email html (#92372)

Alex V02c1820576b4
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.py
index 86eda027cc2d..e79c801bba50 100644
--- a/products/conversations/backend/api/email_events.py
+++ b/products/conversations/backend/api/email_events.py
@@ -43,6 +43,7 @@ from products.conversations.backend.services.email_channel_setup import (
capture_google_forwarding_confirmation,
process_forwarding_challenges,
)
+from products.conversations.backend.services.email_links import recover_links_from_html
from products.conversations.backend.services.email_thread_ingestion import (
EmailAddress,
ParsedEmail,
@@ -459,6 +460,8 @@ def _parse_inbound_email(request: HttpRequest, config: EmailChannel) -> ParsedEm
subject=request.POST.get("subject", "")[:500],
body_plain=request.POST.get("body-plain", "")[:MAX_EMAIL_BODY_LENGTH],
stripped_text=stripped_text[:MAX_EMAIL_BODY_LENGTH],
+ body_html=request.POST.get("body-html", "")[:MAX_EMAIL_BODY_LENGTH],
+ stripped_html=request.POST.get("stripped-html", "")[:MAX_EMAIL_BODY_LENGTH],
sender_authenticated=_sender_authenticated(request, sender_email),
dkim_passed=_mailgun_authentication_passed(request, "X-Mailgun-Dkim-Check-Result"),
dkim_signing_domains=_dkim_signing_domains(request),
@@ -538,10 +541,8 @@ def _process_support_email(
sender_email=sender_email,
)
- if existing_ticket:
- content = email.stripped_text or email.body_plain
- else:
- content = email.body_plain or email.stripped_text
+ body = email.body_with_matching_html(prefer_stripped=bool(existing_ticket))
+ content = recover_links_from_html(body.text, body.html)
posthog_user = _resolve_team_member(sender_email, team) if email.sender_authenticated else None
is_team_member = posthog_user is not None
diff --git a/products/conversations/backend/services/email_links.py b/products/conversations/backend/services/email_links.py
new file mode 100644
index 000000000000..f45ca310bf7a
--- /dev/null
+++ b/products/conversations/backend/services/email_links.py
@@ -0,0 +1,88 @@
+"""Recover hyperlinks that Mailgun drops when it flattens HTML-only mail.
+
+Mailgun builds `body-plain` for an HTML-only email by stripping tags, which keeps
+the anchor text but loses the `href`. Inbound support and customer-communication
+messages store that plain text, so a call-to-action link (for example an email
+forwarding activation link) never reaches the inbox. We read the links back out
+of `body-html` and fold them into the stored text as Markdown, which the inbox
+already renders. The stripped body is kept as-is, so quoted-reply trimming and
+threading are unaffected.
+"""
+
+from __future__ import annotations
+
+import re
+
+import structlog
+from bs4 import BeautifulSoup
+
+logger = structlog.get_logger(__name__)
+
+_HTTP_SCHEME_RE = re.compile(r"^https?://", re.IGNORECASE)
+# Cap the anchors we scan so a large marketing email can't turn one message into
+# an expensive parse.
+_MAX_ANCHORS = 100
+
+
+def _md_safe_href(href: str) -> str:
+ """Escape the characters that would end a Markdown link destination early."""
+ return href.replace(" ", "%20").replace("(", "%28").replace(")", "%29")
+
+
+def recover_links_from_html(text: str, html: str) -> str:
+ """Fold links from `html` into `text` as Markdown when they were lost.
+
+ Only a link whose URL is missing from `text` and whose anchor text still
+ appears verbatim in `text` is rewritten, once, to `[label](href)`. Anything
+ else is left untouched, so already-linked URLs and stripped quotes are safe.
+ """
+ if not text or not html:
+ return text
+
+ try:
+ soup = BeautifulSoup(html, "html.parser")
+ except Exception: # noqa: BLE001 — a malformed HTML part must never fail ingestion
+ logger.info("conversations.email_links.parse_failed")
+ return text
+
+ candidates: list[tuple[str, str]] = []
+ seen_labels: set[str] = set()
+ for anchor in soup.find_all("a")[:_MAX_ANCHORS]:
+ href = (anchor.get("href") or "").strip()
+ if not href or not _HTTP_SCHEME_RE.match(href):
+ continue
+ label = anchor.get_text(separator=" ", strip=True)
+ # Skip an unusable label, a URL that already survived into the text, or a
+ # label seen already (its first anchor wins).
+ if not label or "[" in label or "]" in label or href in text or label in seen_labels:
+ continue
+ seen_labels.add(label)
+ candidates.append((label, href))
+
+ if not candidates:
+ return text
+
+ # Rewrite left to right on the not-yet-emitted suffix only, so a later label
+ # can never match inside a link or URL we already inserted. Each pass links
+ # the earliest remaining label occurrence; earliest position wins on ties.
+ parts: list[str] = []
+ remaining = text
+ used: set[str] = set()
+ while True:
+ best: tuple[int, str, str] | None = None
+ for label, href in candidates:
+ if label in used:
+ continue
+ index = remaining.find(label)
+ if index != -1 and (best is None or index < best[0]):
+ best = (index, label, href)
+ if best is None:
+ break
+ index, label, href = best
+ parts.append(remaining[:index])
+ parts.append(f"[{label}]({_md_safe_href(href)})")
+ remaining = remaining[index + len(label) :]
+ used.add(label)
+ parts.append(remaining)
+
+ return "".join(parts)
diff --git a/products/conversations/backend/services/email_thread_ingestion.py b/products/conversations/backend/services/email_thread_ingestion.py
index 710c24831987..dfe4d07765ed 100644
--- a/products/conversations/backend/services/email_thread_ingestion.py
+++ b/products/conversations/backend/services/email_thread_ingestion.py
@@ -19,6 +19,7 @@ from products.conversations.backend.models import (
EmailThreadParticipant,
EmailThreadParticipantKind,
)
+from products.conversations.backend.services.email_links import recover_links_from_html
from products.customer_analytics.backend.facade.email_matching import (
schedule_email_thread_link_recalculation_for_threads,
)
@@ -33,6 +34,12 @@ class EmailAddress:
return {"name": self.name, "email": self.email}
+@dataclass(frozen=True, kw_only=True)
+class EmailBody:
+ text: str
+ html: str
+
+
@dataclass(frozen=True, kw_only=True)
class ParsedEmail:
message_id: str
@@ -45,6 +52,8 @@ class ParsedEmail:
subject: str
body_plain: str
stripped_text: str
+ body_html: str = ""
+ stripped_html: str = ""
sender_authenticated: bool
dkim_passed: bool
dkim_signing_domains: tuple[str, ...]
@@ -52,6 +61,21 @@ class ParsedEmail:
attachments: tuple[UploadedFile, ...]
forwarding_challenge_tokens: tuple[str, ...] = ()
+ def body_with_matching_html(self, *, prefer_stripped: bool) -> "EmailBody":
+ """Return the body text we store paired with the HTML of the same scope.
+
+ Link recovery must never scan a wider HTML than the text it rewrites: the
+ stripped body drops quoted history, so pairing it with the full `body_html`
+ would attach a historical URL to current prose. `stripped_html` covers the
+ same new part; `body_html` is the fallback when no stripped HTML exists (for
+ example Gmail sync, whose text is never quote-stripped).
+ """
+ if prefer_stripped and self.stripped_text:
+ return EmailBody(text=self.stripped_text, html=self.stripped_html or self.body_html)
+ if self.body_plain:
+ return EmailBody(text=self.body_plain, html=self.body_html or self.stripped_html)
+ return EmailBody(text=self.stripped_text, html=self.stripped_html or self.body_html)
+
@dataclass(frozen=True, kw_only=True)
class EmailThreadIngestionResult:
@@ -183,9 +207,8 @@ def _upsert_participants(
def _message_content(*, thread: EmailThread, email: ParsedEmail) -> str:
- if thread.message_count > 0:
- return email.stripped_text or email.body_plain
- return email.body_plain or email.stripped_text
+ body = email.body_with_matching_html(prefer_stripped=thread.message_count > 0)
+ return recover_links_from_html(body.text, body.html)
def _update_thread_summary(*, thread: EmailThread, email: ParsedEmail, content: str) -> None:
diff --git a/products/conversations/backend/services/gmail_sync.py b/products/conversations/backend/services/gmail_sync.py
index edb8c9848250..ffa01682f177 100644
--- a/products/conversations/backend/services/gmail_sync.py
+++ b/products/conversations/backend/services/gmail_sync.py
@@ -395,6 +395,7 @@ def _parse_gmail_message(
subject=_decode_header(headers.get("subject", ""))[:500],
body_plain=body_plain[:50_000],
stripped_text=body_plain[:50_000],
+ body_html=(bodies.html or "")[:50_000],
sender_authenticated=False,
dkim_passed=False,
dkim_signing_domains=(),
diff --git a/products/conversations/backend/tests/test_email_links.py b/products/conversations/backend/tests/test_email_links.py
new file mode 100644
index 000000000000..9381f964bb3e
--- /dev/null
+++ b/products/conversations/backend/tests/test_email_links.py
@@ -0,0 +1,121 @@
+from datetime import UTC, datetime
+
+from parameterized import parameterized
+
+from products.conversations.backend.services.email_links import recover_links_from_html
+from products.conversations.backend.services.email_thread_ingestion import EmailAddress, ParsedEmail
+
+
+def _email(**overrides: object) -> ParsedEmail:
+ defaults: dict[str, object] = {
+ "message_id": "<[email protected]>",
+ "in_reply_to": None,
+ "references": (),
+ "sent_at": datetime(2026, 1, 1, tzinfo=UTC),
+ "sender": EmailAddress(name="Sender", email="[email protected]"),
+ "to_recipients": (),
+ "cc_recipients": (),
+ "subject": "Re: forwarding",
+ "body_plain": "",
+ "stripped_text": "",
+ "body_html": "",
+ "stripped_html": "",
+ "sender_authenticated": False,
+ "dkim_passed": False,
+ "dkim_signing_domains": (),
+ "capture_address": "[email protected]",
+ "attachments": (),
+ }
+ defaults.update(overrides)
+ return ParsedEmail(**defaults) # type: ignore[arg-type]
+
+
+class TestRecoverLinksFromHtml:
+ def test_recovers_link_dropped_from_flattened_plain_text(self) -> None:
+ text = "Please confirm the forward.\nAttiva l'inoltro\nThanks"
+ html = '<p>Please confirm the forward.</p><a href="https://host.example/activate?t=abc">Attiva l\'inoltro</a>'
+ result = recover_links_from_html(text, html)
+ assert "[Attiva l'inoltro](https://host.example/activate?t=abc)" in result
+
+ def test_leaves_text_untouched_when_url_already_present(self) -> None:
+ text = "Confirm at https://host.example/activate?t=abc now"
+ html = '<a href="https://host.example/activate?t=abc">Confirm</a>'
+ assert recover_links_from_html(text, html) == text
+
+ def test_only_first_occurrence_is_linked(self) -> None:
+ text = "click here and also click here"
+ html = '<a href="https://host.example/go">click here</a>'
+ result = recover_links_from_html(text, html)
+ assert result == "[click here](https://host.example/go) and also click here"
+
+ @parameterized.expand(
+ [
+ ("no_html", "just text", ""),
+ ("no_text", "", "<a href='https://host.example'>x</a>"),
+ ]
+ )
+ def test_noop_without_both_sides(self, _name: str, text: str, html: str) -> None:
+ assert recover_links_from_html(text, html) == text
+
+ def test_ignores_non_http_and_labelless_anchors(self) -> None:
+ text = "mail me or open the app"
+ html = '<a href="mailto:[email protected]">mail me</a><a href="https://host.example"></a>'
+ assert recover_links_from_html(text, html) == text
+
+ def test_skips_label_missing_from_text(self) -> None:
+ text = "Only the footer survived"
+ html = '<a href="https://host.example/cta">Activate now</a>'
+ assert recover_links_from_html(text, html) == text
+
+ def test_does_not_nest_when_label_is_substring_of_another(self) -> None:
+ text = "Attiva l'inoltro"
+ html = (
+ '<a href="https://host.example/activate">Attiva l\'inoltro</a>'
+ '<a href="https://host.example/other">inoltro</a>'
+ )
+ result = recover_links_from_html(text, html)
+ assert result == "[Attiva l'inoltro](https://host.example/activate)"
+
+ def test_escapes_parentheses_in_href(self) -> None:
+ text = "Read the docs here"
+ html = '<a href="https://host.example/wiki/Foo_(bar)">Read the docs here</a>'
+ result = recover_links_from_html(text, html)
+ assert result == "[Read the docs here](https://host.example/wiki/Foo_%28bar%29)"
+
+ def test_reply_ignores_links_from_quoted_history(self) -> None:
+ # A reply's stripped text drops the quoted history; the matching HTML must
+ # too, so a label reused in the new prose keeps no historical URL.
+ email = _email(
+ stripped_text="Thanks, click here to finish.",
+ stripped_html='<p>Thanks, <a href="https://host.example/new">click here</a> to finish.</p>',
+ body_plain="Thanks, click here to finish.\nOn Mon you wrote: click here",
+ body_html=(
+ '<p>Thanks, <a href="https://host.example/new">click here</a> to finish.</p>'
+ '<blockquote>On Mon you wrote: <a href="https://old.example/stale">click here</a></blockquote>'
+ ),
+ )
+ body = email.body_with_matching_html(prefer_stripped=True)
+ result = recover_links_from_html(body.text, body.html)
+ assert result == "Thanks, [click here](https://host.example/new) to finish."
+ assert "old.example" not in result
+
+ def test_new_ticket_uses_full_body_html(self) -> None:
+ email = _email(
+ body_plain="Please confirm.\nAttiva l'inoltro",
+ body_html='<p>Please confirm.</p><a href="https://host.example/activate">Attiva l\'inoltro</a>',
+ )
+ body = email.body_with_matching_html(prefer_stripped=False)
+ result = recover_links_from_html(body.text, body.html)
+ assert "[Attiva l'inoltro](https://host.example/activate)" in result
+
+ def test_links_earliest_occurrence_across_multiple_labels(self) -> None:
+ text = "First open the guide then confirm your account"
+ html = (
+ '<a href="https://host.example/confirm">confirm your account</a>'
+ '<a href="https://host.example/guide">the guide</a>'
+ )
+ result = recover_links_from_html(text, html)
+ assert result == (
+ "First open [the guide](https://host.example/guide) then "
+ "[confirm your account](https://host.example/confirm)"
+ )