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.

feat(conversations): capture customer email threads (#80761)

Arthur Moreira de Deus3eb43b8d5449
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index f5a6fd8937f2..1ab006075234 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -137,6 +137,7 @@ rules:
|DeploymentProject
|EarlyAccessFeature
|EmailMessageMapping
+ |EmailChannelSetup
|EmailThread
|EmailThreadMessage
|EmailThreadParticipant
@@ -498,6 +499,7 @@ rules:
|DeploymentProject
|EarlyAccessFeature
|EmailMessageMapping
+ |EmailChannelSetup
|EmailThread
|EmailThreadMessage
|EmailThreadParticipant
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.py
index 41109348753f..9758edf4abcd 100644
--- a/products/conversations/backend/api/email_events.py
+++ b/products/conversations/backend/api/email_events.py
@@ -1,13 +1,16 @@
"""Inbound email webhook endpoint for Mailgun routes."""
import re
-from email.utils import getaddresses, parseaddr
+import json
+from datetime import UTC, datetime, timedelta
+from email.utils import getaddresses, parseaddr, parsedate_to_datetime
from typing import Any, cast
from django.core.files.uploadedfile import UploadedFile
from django.db import IntegrityError, transaction
from django.db.models import F
from django.http import HttpRequest, HttpResponse
+from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
import structlog
@@ -18,12 +21,25 @@ from posthog.models.team import Team
from posthog.models.user import User
from products.conversations.backend.mailgun import validate_webhook_signature
-from products.conversations.backend.models import Channel, EmailChannel, EmailChannelKind, EmailMessageMapping, Status
+from products.conversations.backend.models import (
+ Channel,
+ EmailChannel,
+ EmailChannelConnectionStatus,
+ EmailChannelKind,
+ EmailMessageMapping,
+ Status,
+)
from products.conversations.backend.models.ticket import Ticket
from products.conversations.backend.services.attachments import (
sanitize_attachment_filename,
save_file_to_uploaded_media,
)
+from products.conversations.backend.services.email_channel_setup import capture_google_forwarding_confirmation
+from products.conversations.backend.services.email_thread_ingestion import (
+ EmailAddress,
+ ParsedInboundEmail,
+ ingest_customer_email,
+)
from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region
logger = structlog.get_logger(__name__)
@@ -31,9 +47,18 @@ logger = structlog.get_logger(__name__)
INBOUND_TOKEN_PATTERN = re.compile(r"^team-([a-f0-9]+)@")
_VIA_SUFFIX_RE = re.compile(r"\s+via\s+.+$", re.IGNORECASE)
_BASIC_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+_MESSAGE_ID_RE = re.compile(r"<[^<>\s]+>")
MAX_EMAIL_BODY_LENGTH = 50_000
MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024 # 10 MB per file
MAX_ATTACHMENTS = 20
+# Sender-controlled To/Cc headers can list far more addresses than a real thread carries, and each
+# one becomes a per-recipient participant upsert. Cap the count so one message can't fan out into
+# an unbounded batch of queries under the held thread lock.
+MAX_RECIPIENTS = 100
+# The sender controls the Date header, so a far-future value would latch a thread's last_message_at
+# and freeze its preview. Reject dates beyond a small clock-skew allowance and fall back to the
+# authenticated webhook timestamp (or now) instead.
+MAX_SENT_AT_CLOCK_SKEW = timedelta(minutes=5)
def _extract_inbound_token(recipient: str) -> str | None:
@@ -44,14 +69,14 @@ def _extract_inbound_token(recipient: str) -> str | None:
def _find_thread_ticket(
team_id: int,
in_reply_to: str | None,
- references: str | None,
+ references: tuple[str, ...],
) -> Ticket | None:
"""Look up an existing ticket via email threading headers."""
# Try In-Reply-To first (most specific)
if in_reply_to:
mapping = (
EmailMessageMapping.objects.filter(
- message_id=in_reply_to.strip(),
+ message_id=in_reply_to,
team_id=team_id,
)
.select_related("ticket")
@@ -60,28 +85,26 @@ def _find_thread_ticket(
if mapping:
return mapping.ticket
- # Fall back to References (space-separated list of message-ids, newest last)
+ # Fall back to References (newest last)
if references:
- ref_ids = [r.strip() for r in references.strip().split()]
mapping_by_id = {
m.message_id: m
for m in EmailMessageMapping.objects.filter(
- message_id__in=ref_ids,
+ message_id__in=references,
team_id=team_id,
).select_related("ticket")
}
- for ref_id in reversed(ref_ids):
+ for ref_id in reversed(references):
if ref_id in mapping_by_id:
return mapping_by_id[ref_id].ticket
return None
-def _extract_attachments(request: HttpRequest, team: Team) -> list[dict[str, Any]]:
- """Read file uploads from the Mailgun webhook and persist them."""
+def _extract_attachments(uploaded_files: tuple[UploadedFile, ...], team: Team) -> list[dict[str, Any]]:
+ """Persist files from the Mailgun webhook within the configured limits."""
attachments: list[dict[str, Any]] = []
- for _key in list(request.FILES.keys())[:MAX_ATTACHMENTS]:
- uploaded_file = cast(UploadedFile, request.FILES[_key])
+ for uploaded_file in uploaded_files:
if uploaded_file.size is not None and uploaded_file.size > MAX_ATTACHMENT_SIZE:
logger.warning(
"email_inbound_attachment_too_large",
@@ -239,7 +262,7 @@ def _sender_authenticated(request: HttpRequest, sender_email: str) -> bool:
An attacker signing with evil.com's key but forging From: [email protected]
would still get DKIM Pass.
"""
- spf_passed = request.POST.get("X-Mailgun-Spf", "").lower() == "pass"
+ spf_passed = _mailgun_authentication_passed(request, "X-Mailgun-Spf")
if not spf_passed:
return False
envelope_sender = request.POST.get("sender", "")
@@ -248,9 +271,153 @@ def _sender_authenticated(request: HttpRequest, sender_email: str) -> bool:
return bool(envelope_domain and from_domain and envelope_domain == from_domain)
+def _parse_message_ids(value: str) -> tuple[str, ...]:
+ message_ids = _MESSAGE_ID_RE.findall(value)
+ if not message_ids:
+ message_ids = value.split()
+ return tuple(dict.fromkeys(message_id.strip()[:998] for message_id in message_ids if message_id.strip()))
+
+
+def _message_header_values(request: HttpRequest, header_name: str) -> tuple[str, ...]:
+ values: list[str] = []
+ direct_value = request.POST.get(header_name, "")
+ if direct_value:
+ values.append(direct_value)
+
+ raw_headers = request.POST.get("message-headers", "")
+ if raw_headers:
+ try:
+ parsed_headers = json.loads(raw_headers)
+ except (TypeError, ValueError):
+ parsed_headers = []
+ if isinstance(parsed_headers, list):
+ for header in parsed_headers:
+ if (
+ isinstance(header, list)
+ and len(header) == 2
+ and isinstance(header[0], str)
+ and isinstance(header[1], str)
+ and header[0].lower() == header_name.lower()
+ ):
+ values.append(header[1])
+ return tuple(dict.fromkeys(values))
+
+
+def _mailgun_authentication_passed(request: HttpRequest, header_name: str) -> bool:
+ results = tuple(
+ dict.fromkeys(value.strip().lower() for value in _message_header_values(request, header_name) if value.strip())
+ )
+ return results == ("pass",)
+
+
+def _dkim_signing_domains(request: HttpRequest) -> tuple[str, ...]:
+ domains: list[str] = []
+ for signature in _message_header_values(request, "DKIM-Signature"):
+ tags: dict[str, str] = {}
+ for raw_tag in signature.split(";"):
+ key, separator, value = raw_tag.partition("=")
+ if separator:
+ tags[key.strip().lower()] = value.strip()
+ signed_headers = {header.strip().lower() for header in tags.get("h", "").split(":")}
+ domain = tags.get("d", "").rstrip(".").lower()
+ if not domain or not {"from", "subject"}.issubset(signed_headers) or "l" in tags:
+ return ()
+ domains.append(domain)
+ return tuple(dict.fromkeys(domains))
+
+
+def _parse_addresses(value: str) -> tuple[EmailAddress, ...]:
+ addresses: list[EmailAddress] = []
+ seen: set[str] = set()
+ for name, address in getaddresses([value]):
+ normalized_email = address.strip().lower()[:400]
+ if not normalized_email or normalized_email in seen:
+ continue
+ seen.add(normalized_email)
+ addresses.append(EmailAddress(name=name.strip()[:400], email=normalized_email))
+ if len(addresses) >= MAX_RECIPIENTS:
+ break
+ return tuple(addresses)
+
+
+def _parse_sent_at(request: HttpRequest) -> datetime:
+ now = timezone.now()
+ date_header = request.POST.get("Date", "") or request.POST.get("date", "")
+ if date_header:
+ try:
+ sent_at = parsedate_to_datetime(date_header)
+ if sent_at.tzinfo is None:
+ sent_at = sent_at.replace(tzinfo=UTC)
+ if sent_at <= now + MAX_SENT_AT_CLOCK_SKEW:
+ return sent_at
+ logger.warning("email_inbound_future_date_header")
+ except (TypeError, ValueError, OverflowError):
+ logger.warning("email_inbound_invalid_date_header")
+
+ webhook_timestamp = request.POST.get("timestamp", "")
+ if webhook_timestamp:
+ try:
+ return datetime.fromtimestamp(float(webhook_timestamp), tz=UTC)
+ except (ValueError, OverflowError):
+ logger.warning("email_inbound_invalid_timestamp")
+ return now
+
+
+def _parse_inbound_email(request: HttpRequest, config: EmailChannel) -> ParsedInboundEmail | None:
+ message_ids = _parse_message_ids(request.POST.get("Message-Id", ""))
+ if not message_ids:
+ return None
+
+ from_header = request.POST.get("from", "")
+ sender_name, sender_email = parseaddr(from_header)
+ if not sender_email:
+ sender_email = request.POST.get("sender", "")
+ sender_email = sender_email.strip().lower()[:400]
+ if not sender_name:
+ sender_name = sender_email.split("@")[0] if sender_email else "Unknown"
+ sender_email, sender_name = _recover_dmarc_rewritten_sender(request, config, sender_email, sender_name)
+
+ stripped_text = request.POST.get("stripped-text", "")
+ stripped_signature = request.POST.get("stripped-signature", "")
+ if stripped_signature and stripped_text:
+ stripped_text = f"{stripped_text}\n\n{stripped_signature}"
+
+ in_reply_to_ids = _parse_message_ids(request.POST.get("In-Reply-To", ""))
+ attachments: list[UploadedFile] = []
+ for key in list(request.FILES.keys())[:MAX_ATTACHMENTS]:
+ uploaded_file = cast(UploadedFile, request.FILES[key])
+ if uploaded_file.size is not None and uploaded_file.size > MAX_ATTACHMENT_SIZE:
+ logger.warning(
+ "email_inbound_attachment_too_large",
+ team_id=config.team_id,
+ file_name=uploaded_file.name,
+ size=uploaded_file.size,
+ )
+ continue
+ attachments.append(uploaded_file)
+
+ return ParsedInboundEmail(
+ message_id=message_ids[0],
+ in_reply_to=in_reply_to_ids[0] if in_reply_to_ids else None,
+ references=_parse_message_ids(request.POST.get("References", "")),
+ sent_at=_parse_sent_at(request),
+ sender=EmailAddress(name=sender_name[:400], email=sender_email),
+ to_recipients=_parse_addresses(request.POST.get("To", "")),
+ cc_recipients=_parse_addresses(request.POST.get("Cc", "")),
+ 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],
+ 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),
+ capture_address=request.POST.get("recipient", "").strip().lower(),
+ attachments=tuple(attachments),
+ )
+
+
def _collect_participants(
- to_header: str,
- cc_header: str,
+ to_recipients: tuple[EmailAddress, ...],
+ cc_recipients: tuple[EmailAddress, ...],
inbound_token: str,
channel_email: str,
sender_email: str,
@@ -267,8 +434,8 @@ def _collect_participants(
team_inbound_address = f"team-{inbound_token}@"
excluded = {channel_email.lower(), sender_email.lower()}
participants: list[str] = []
- for _name, addr in getaddresses([to_header, cc_header]):
- low = addr.lower()
+ for recipient in (*to_recipients, *cc_recipients):
+ low = recipient.email.lower()
if not low or low in excluded or low.startswith(team_inbound_address):
continue
if low not in participants:
@@ -291,117 +458,44 @@ def _resolve_team_member(email: str, team: Team) -> User | None:
return membership.user if membership else None
-@csrf_exempt
-def email_inbound_handler(request: HttpRequest) -> HttpResponse:
- if request.method != "POST":
- return HttpResponse(status=405)
-
- # 1. Authenticate webhook
- token = request.POST.get("token", "")
- timestamp = request.POST.get("timestamp", "")
- signature = request.POST.get("signature", "")
-
- if not validate_webhook_signature(token, timestamp, signature):
- logger.warning("email_inbound_invalid_signature")
- return HttpResponse("Invalid signature", status=403)
-
- # 2. Route to team via recipient address
- recipient = request.POST.get("recipient", "")
- inbound_token = _extract_inbound_token(recipient)
- if not inbound_token:
- logger.warning("email_inbound_no_token", recipient=recipient)
- return HttpResponse("Invalid recipient", status=400)
-
- try:
- config = EmailChannel.objects.select_related("team").get(inbound_token=inbound_token)
- except EmailChannel.DoesNotExist:
- if is_primary_region(request):
- success = proxy_to_secondary_region(request, log_prefix="email_inbound", timeout=10)
- return HttpResponse(status=200 if success else 502)
- logger.warning("email_inbound_unknown_token", inbound_token=inbound_token)
- return HttpResponse("Unknown recipient", status=404)
-
+def _process_support_email(
+ *,
+ config: EmailChannel,
+ inbound_token: str,
+ email: ParsedInboundEmail,
+) -> HttpResponse:
team = config.team
- if config.kind != EmailChannelKind.SUPPORT:
- logger.info("email_inbound_customer_communication_deferred", team_id=team.id, config_id=str(config.id))
- return HttpResponse(status=200)
-
- # 3. Check email_enabled
settings_dict = team.conversations_settings or {}
if not settings_dict.get("email_enabled"):
logger.info("email_inbound_disabled", team_id=team.id)
return HttpResponse(status=200)
- # 4. Deduplicate by Message-Id
- email_message_id = request.POST.get("Message-Id", "").strip()
- if not email_message_id:
- logger.warning("email_inbound_no_message_id", team_id=team.id)
- return HttpResponse(status=200)
-
- if EmailMessageMapping.objects.filter(message_id=email_message_id, team=team).exists():
- logger.info("email_inbound_duplicate", message_id=email_message_id)
+ if EmailMessageMapping.objects.filter(message_id=email.message_id, team=team).exists():
+ logger.info("email_inbound_duplicate", message_id=email.message_id)
return HttpResponse(status=200)
- # 5. Thread matching
- in_reply_to = request.POST.get("In-Reply-To")
- references = request.POST.get("References")
- existing_ticket = _find_thread_ticket(team.id, in_reply_to, references)
-
- # 6. Parse sender
- from_header = request.POST.get("from", "")
- sender_name, sender_email = parseaddr(from_header)
- if not sender_email:
- sender_email = request.POST.get("sender", "")
- if not sender_name:
- sender_name = sender_email.split("@")[0] if sender_email else "Unknown"
-
- # 6a. Recover original sender when From was rewritten by DMARC-compliant
- # forwarding (e.g. Google Groups rewrites From to the group address for
- # senders whose domain has p=quarantine or p=reject).
- sender_email, sender_name = _recover_dmarc_rewritten_sender(request, config, sender_email, sender_name)
-
- # 6b. Parse other thread participants from To + Cc. We fold both into a single
- # list (dropping the support inbox itself and the sender) so a direct recipient
- # who only CC'd the support address still shows up and stays on replies.
+ existing_ticket = _find_thread_ticket(team.id, email.in_reply_to, email.references)
+ sender_name = email.sender.name
+ sender_email = email.sender.email
cc_list = _collect_participants(
- to_header=request.POST.get("To", ""),
- cc_header=request.POST.get("Cc", ""),
+ to_recipients=email.to_recipients,
+ cc_recipients=email.cc_recipients,
inbound_token=inbound_token,
channel_email=config.from_email,
sender_email=sender_email,
)
- # 7. Get content. Mailgun's stripped-text removes quoted parts, which is right for
- # replies (the quoted trail is the thread we already store) but wrong for a first
- # message: a forwarded email's original content lives in the "quoted" block, so
- # stripping would drop the very context the customer forwarded in. Keep the full
- # plain body for new tickets; strip quotes only on replies to existing tickets.
- # Mailgun's signature detection also cuts real content (e.g. a trailing list of
- # bare emails/links), so reattach stripped-signature after stripped-text.
- body_plain = request.POST.get("body-plain", "")
- stripped_text = request.POST.get("stripped-text", "")
- stripped_signature = request.POST.get("stripped-signature", "")
- if stripped_signature and stripped_text:
- stripped_text = f"{stripped_text}\n\n{stripped_signature}"
if existing_ticket:
- content = stripped_text or body_plain
+ content = email.stripped_text or email.body_plain
else:
- content = body_plain or stripped_text
- content = content[:MAX_EMAIL_BODY_LENGTH]
- subject = request.POST.get("subject", "")[:500]
-
- # 7b. Detect team member sender — only trust From when DKIM passes
- # AND the envelope-sender domain aligns with the From domain.
- sender_authenticated = _sender_authenticated(request, sender_email)
- posthog_user = _resolve_team_member(sender_email, team) if sender_authenticated else None
+ content = email.body_plain or email.stripped_text
+
+ posthog_user = _resolve_team_member(sender_email, team) if email.sender_authenticated else None
is_team_member = posthog_user is not None
- # 8. Create ticket/comment/mapping in a transaction
- # Attachments are extracted inside the transaction so UploadedMedia rows roll back
- # on duplicate-race IntegrityError. Orphaned S3 blobs are acceptable.
try:
with transaction.atomic():
- attachments = _extract_attachments(request, team)
+ attachments = _extract_attachments(email.attachments, team)
content, rich_content = _build_content_with_attachments(content, attachments)
ticket: Ticket | None = None
@@ -422,14 +516,14 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
"name": sender_name,
"email": sender_email,
},
- email_subject=subject,
+ email_subject=email.subject,
email_from=sender_email,
cc_participants=cc_list,
unread_team_count=0 if is_team_member else 1,
- identity_verified=sender_authenticated,
+ identity_verified=email.sender_authenticated,
)
elif (
- sender_authenticated
+ email.sender_authenticated
and not ticket.identity_verified
and sender_email.lower() == (ticket.email_from or ticket.distinct_id or "").lower()
):
@@ -448,7 +542,7 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
"from_email": True,
"email_from": sender_email,
"email_from_name": sender_name,
- "email_message_id": email_message_id,
+ "email_message_id": email.message_id,
"email_attachments": attachments if attachments else None,
}
@@ -480,13 +574,13 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
qs.update(cc_participants=list(dict.fromkeys(ticket.cc_participants + cc_list)))
EmailMessageMapping.objects.create(
- message_id=email_message_id,
+ message_id=email.message_id,
team=team,
ticket=ticket,
comment=comment,
)
except IntegrityError:
- logger.info("email_inbound_duplicate_race", message_id=email_message_id)
+ logger.info("email_inbound_duplicate_race", message_id=email.message_id)
return HttpResponse(status=200)
logger.info(
@@ -495,5 +589,78 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
ticket_id=str(ticket.id),
is_reply=existing_ticket is not None,
)
-
return HttpResponse(status=200)
+
+
+@csrf_exempt
+def email_inbound_handler(request: HttpRequest) -> HttpResponse:
+ if request.method != "POST":
+ return HttpResponse(status=405)
+
+ token = request.POST.get("token", "")
+ timestamp = request.POST.get("timestamp", "")
+ signature = request.POST.get("signature", "")
+ if not validate_webhook_signature(token, timestamp, signature):
+ logger.warning("email_inbound_invalid_signature")
+ return HttpResponse("Invalid signature", status=403)
+
+ recipient = request.POST.get("recipient", "")
+ inbound_token = _extract_inbound_token(recipient)
+ if not inbound_token:
+ logger.warning("email_inbound_no_token", recipient=recipient)
+ return HttpResponse("Invalid recipient", status=400)
+
+ try:
+ config = EmailChannel.objects.select_related("team", "owner").get(inbound_token=inbound_token)
+ except EmailChannel.DoesNotExist:
+ if is_primary_region(request):
+ success = proxy_to_secondary_region(request, log_prefix="email_inbound", timeout=10)
+ return HttpResponse(status=200 if success else 502)
+ logger.warning("email_inbound_unknown_token", inbound_token=inbound_token)
+ return HttpResponse("Unknown recipient", status=404)
+
+ email = _parse_inbound_email(request, config)
+ if email is None:
+ logger.warning("email_inbound_no_message_id", team_id=config.team_id)
+ return HttpResponse(status=200)
+
+ if config.kind == EmailChannelKind.CUSTOMER_COMMUNICATION:
+ if config.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION:
+ captured = capture_google_forwarding_confirmation(
+ team_id=config.team_id,
+ channel=config,
+ email=email,
+ )
+ logger.info(
+ "customer_email_confirmation_candidate_processed",
+ team_id=config.team_id,
+ config_id=str(config.id),
+ captured=captured,
+ )
+ return HttpResponse(status=200)
+ if config.connection_status != EmailChannelConnectionStatus.ACTIVE:
+ return HttpResponse(status=200)
+
+ try:
+ result = ingest_customer_email(team_id=config.team_id, channel=config, email=email)
+ except ValueError as error:
+ # A misconfigured channel (e.g. a dangling owner) can't be fixed by redelivery, so log
+ # and ack rather than 500 into a Mailgun retry loop.
+ logger.warning(
+ "customer_email_channel_misconfigured",
+ team_id=config.team_id,
+ config_id=str(config.id),
+ error=str(error),
+ )
+ return HttpResponse(status=200)
+ logger.info(
+ "customer_email_inbound_processed",
+ team_id=config.team_id,
+ config_id=str(config.id),
+ thread_id=str(result.thread_id),
+ message_id=str(result.message_id),
+ created=result.created,
+ )
+ return HttpResponse(status=200)
+
+ return _process_support_email(config=config, inbound_token=inbound_token, email=email)
diff --git a/products/conversations/backend/api/tests/test_customer_email_ingestion.py b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
new file mode 100644
index 000000000000..ddc16e753e87
--- /dev/null
+++ b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
@@ -0,0 +1,338 @@
+import json
+from datetime import UTC, datetime, timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.test import Client, RequestFactory, SimpleTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.comment import Comment
+from posthog.models.organization import OrganizationMembership
+from posthog.models.user import User
+
+from products.conversations.backend.api.email_events import MAX_RECIPIENTS, _parse_addresses, _parse_sent_at
+from products.conversations.backend.models import (
+ EMAIL_THREAD_COMMENT_SCOPE,
+ EmailChannel,
+ EmailChannelConnectionStatus,
+ EmailChannelKind,
+ EmailChannelSetup,
+ EmailChannelSetupProvider,
+ EmailOutboxMessage,
+ EmailThread,
+ EmailThreadMessage,
+ Ticket,
+)
+
+
+class TestCustomerEmailIngestion(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.client = Client()
+ self.channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="c0570a111",
+ from_email="[email protected]",
+ from_name="Customer success",
+ domain="example.com",
+ domain_verified=True,
+ connection_status=EmailChannelConnectionStatus.ACTIVE,
+ )
+ signature_patcher = patch(
+ "products.conversations.backend.api.email_events.validate_webhook_signature",
+ return_value=True,
+ )
+ signature_patcher.start()
+ self.addCleanup(signature_patcher.stop)
+
+ def _post_email(
+ self,
+ *,
+ message_id: str,
+ recipient: str = "[email protected]",
+ **overrides: str,
+ ):
+ data = {
+ "token": "webhook-token",
+ "timestamp": "1749565800",
+ "signature": "webhook-signature",
+ "recipient": recipient,
+ "from": "Example customer <[email protected]>",
+ "sender": "[email protected]",
+ "To": "CSM <[email protected]>",
+ "Message-Id": message_id,
+ "Date": "Tue, 10 Jun 2025 14:30:00 +0000",
+ "subject": "Account question",
+ "stripped-text": "Can you help?",
+ "body-plain": "Can you help?",
+ }
+ data.update(overrides)
+ return self.client.post("/api/conversations/v1/email/inbound", data)
+
+ def _start_google_setup(self, *, expires_at=None) -> EmailChannelSetup:
+ self.channel.connection_status = EmailChannelConnectionStatus.PENDING_CONFIRMATION
+ self.channel.save(update_fields=["connection_status"])
+ return EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=self.channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=expires_at or timezone.now() + timedelta(hours=24),
+ )
+
+ def _valid_google_confirmation(self, *, action_suffix: str = "expected") -> dict[str, str]:
+ action = f"https://mail-settings.google.com/mail/vf-{action_suffix}"
+ return {
+ "from": "Gmail forwarding <[email protected]>",
+ "sender": "[email protected]",
+ "subject": "(#12345678) Gmail Forwarding Confirmation - Receive Mail from [email protected]",
+ "body-plain": f"Confirm forwarding by visiting {action}",
+ "stripped-text": f"Confirm forwarding by visiting {action}",
+ "X-Mailgun-Spf": "pass",
+ "X-Mailgun-Dkim-Check-Result": "pass",
+ "DKIM-Signature": ("v=1; a=rsa-sha256; d=google.com; s=20230601; h=from:to:subject:date; b=signature"),
+ }
+
+ def test_pending_channel_stores_only_the_first_authenticated_google_confirmation(self) -> None:
+ setup = self._start_google_setup()
+
+ first_response = self._post_email(
+ message_id="<[email protected]>",
+ **self._valid_google_confirmation(),
+ )
+ second_response = self._post_email(
+ message_id="<[email protected]>",
+ **self._valid_google_confirmation(action_suffix="replacement"),
+ )
+
+ assert first_response.status_code == 200
+ assert second_response.status_code == 200
+ setup.refresh_from_db()
+ assert setup.confirmation_action == "https://mail-settings.google.com/mail/vf-expected"
+ assert setup.confirmation_message_id_hash
+ assert setup.confirmation_received_at is not None
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+ assert not Ticket.objects.filter(team=self.team).exists()
+ assert not EmailOutboxMessage.objects.filter(team=self.team).exists()
+
+ def test_pending_channel_accepts_live_mailgun_confirmation_shape(self) -> None:
+ setup = self._start_google_setup()
+ payload = self._valid_google_confirmation()
+ payload["subject"] = "(PostHog Forwarding Confirmation - Receive Mail from [email protected]"
+ payload["body-plain"] = (
+ "Confirm forwarding at https://mail.google.com/mail/vf-%5Blive_token%5D-value or reject it at "
+ "https://mail.google.com/mail/uf-live-token"
+ )
+ payload["stripped-text"] = payload["body-plain"]
+ payload["message-headers"] = json.dumps(
+ [
+ ["X-Mailgun-Spf", payload.pop("X-Mailgun-Spf")],
+ ["X-Mailgun-Dkim-Check-Result", payload.pop("X-Mailgun-Dkim-Check-Result")],
+ ["DKIM-Signature", payload.pop("DKIM-Signature")],
+ ]
+ )
+
+ response = self._post_email(message_id="<[email protected]>", **payload)
+
+ assert response.status_code == 200
+ setup.refresh_from_db()
+ assert setup.confirmation_action == "https://mail.google.com/mail/vf-%5Blive_token%5D-value"
+ assert setup.confirmation_received_at is not None
+
+ @parameterized.expand(
+ [
+ ("missing_spf", {"X-Mailgun-Spf": ""}),
+ ("wrong_source", {"subject": "Gmail Forwarding Confirmation - Receive Mail from [email protected]"}),
+ (
+ "wrong_dkim_domain",
+ {"DKIM-Signature": "v=1; d=attacker.example; h=from:subject; b=signature"},
+ ),
+ (
+ "unsigned_subject",
+ {"DKIM-Signature": "v=1; d=google.com; h=from:to:date; b=signature"},
+ ),
+ (
+ "conflicting_mailgun_results",
+ {
+ "X-Mailgun-Spf": "fail",
+ "X-Mailgun-Dkim-Check-Result": "fail",
+ "DKIM-Signature": "",
+ "message-headers": json.dumps(
+ [
+ ["X-Mailgun-Spf", "pass"],
+ ["X-Mailgun-Dkim-Check-Result", "pass"],
+ ["DKIM-Signature", "v=1; d=google.com; h=from:subject; b=forged"],
+ ]
+ ),
+ },
+ ),
+ (
+ "mixed_dkim_domains",
+ {
+ "DKIM-Signature": "",
+ "message-headers": json.dumps(
+ [
+ ["DKIM-Signature", "v=1; d=google.com; h=from:subject; b=forged"],
+ ["DKIM-Signature", "v=1; d=attacker.example; h=from:subject; b=valid"],
+ ]
+ ),
+ },
+ ),
+ (
+ "lookalike_action_host",
+ {
+ "body-plain": "https://mail-settings.google.com.attacker.example/mail/vf-token",
+ "stripped-text": "https://mail-settings.google.com.attacker.example/mail/vf-token",
+ },
+ ),
+ ]
+ )
+ def test_pending_channel_discards_untrusted_confirmation_candidates(
+ self, _name: str, overrides: dict[str, str]
+ ) -> None:
+ setup = self._start_google_setup()
+ payload = self._valid_google_confirmation()
+ payload.update(overrides)
+
+ response = self._post_email(message_id=f"<{_name}@gmail.com>", **payload)
+
+ assert response.status_code == 200
+ setup.refresh_from_db()
+ assert setup.confirmation_action is None
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
+ def test_expired_setup_is_deleted_and_discards_email(self) -> None:
+ setup = self._start_google_setup(expires_at=timezone.now() - timedelta(seconds=1))
+
+ response = self._post_email(
+ message_id="<[email protected]>",
+ **self._valid_google_confirmation(),
+ )
+
+ assert response.status_code == 200
+ assert not EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+ self.channel.refresh_from_db()
+ assert self.channel.connection_status == EmailChannelConnectionStatus.CONFIRMATION_EXPIRED
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
+ @parameterized.expand(["in_reply_to", "references"])
+ def test_rfc_reply_headers_continue_the_existing_thread(self, header_kind: str) -> None:
+ root_message_id = f"<root-{header_kind}@customer.example>"
+ root_response = self._post_email(
+ message_id=root_message_id,
+ **{
+ "X-Mailgun-Spf": "pass",
+ "body-plain": "Initial message with forwarded context",
+ "stripped-text": "Initial message",
+ },
+ )
+ reply_fields = {
+ "Date": "Tue, 10 Jun 2025 15:30:00 +0000",
+ "body-plain": "Reply only\n\nOn Tuesday, Customer success wrote:\n> Initial message",
+ "stripped-text": "Reply only",
+ }
+ if header_kind == "in_reply_to":
+ reply_fields["In-Reply-To"] = root_message_id
+ else:
+ reply_fields["References"] = f"<[email protected]> {root_message_id}"
+
+ reply_response = self._post_email(
+ message_id=f"<reply-{header_kind}@customer.example>",
+ **reply_fields,
+ )
+
+ assert root_response.status_code == 200
+ assert reply_response.status_code == 200
+ thread = EmailThread.objects.for_team(self.team.id).get()
+ messages = list(
+ EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread).select_related("comment")
+ )
+ assert thread.message_count == 2
+ assert thread.preview == "Reply only"
+ assert len(messages) == 2
+ assert messages[0].sender_authenticated is True
+ assert messages[0].comment.content == "Initial message with forwarded context"
+ assert messages[1].comment.content == "Reply only"
+ assert messages[1].in_reply_to == (root_message_id if header_kind == "in_reply_to" else None)
+ assert messages[1].references == (
+ [] if header_kind == "in_reply_to" else ["<[email protected]>", root_message_id]
+ )
+
+ def test_duplicate_delivery_creates_one_message_across_customer_channels(self) -> None:
+ message_id = "<[email protected]>"
+ first_response = self._post_email(message_id=message_id)
+ retry_response = self._post_email(message_id=message_id)
+
+ second_owner = User.objects.create(email="[email protected]", current_team=self.team)
+ OrganizationMembership.objects.create(
+ organization=self.organization,
+ user=second_owner,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+ EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=second_owner,
+ inbound_token="5ec00dc5a",
+ from_email=second_owner.email,
+ from_name="Second CSM",
+ domain="example.com",
+ domain_verified=True,
+ connection_status=EmailChannelConnectionStatus.ACTIVE,
+ )
+ second_owner_response = self._post_email(
+ message_id=message_id,
+ recipient="[email protected]",
+ )
+
+ assert first_response.status_code == 200
+ assert retry_response.status_code == 200
+ assert second_owner_response.status_code == 200
+ thread = EmailThread.objects.for_team(self.team.id).get()
+ assert thread.message_count == 1
+ assert EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread).count() == 1
+ assert (
+ Comment.objects.filter(team=self.team, scope=EMAIL_THREAD_COMMENT_SCOPE, item_id=str(thread.id)).count()
+ == 1
+ )
+
+ def test_dangling_owner_is_acked_without_a_server_error(self) -> None:
+ # owner is a db_constraint=False FK, so a deleted owner leaves owner_id pointing at a missing
+ # user while satisfying the not-null check constraint; channel.owner then resolves to None and
+ # ingestion raises. The webhook must ack (200) rather than 500 into a Mailgun retry loop.
+ EmailChannel.objects.filter(id=self.channel.id).update(owner_id=987654321)
+
+ response = self._post_email(message_id="<[email protected]>")
+
+ assert response.status_code == 200
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
+
+class TestParseAddresses(SimpleTestCase):
+ def test_recipient_count_is_capped(self) -> None:
+ header = ", ".join(f"user{index}@example.com" for index in range(MAX_RECIPIENTS + 50))
+
+ parsed = _parse_addresses(header)
+
+ assert len(parsed) == MAX_RECIPIENTS
+
+
+class TestParseSentAt(SimpleTestCase):
+ factory = RequestFactory()
+
+ @parameterized.expand(
+ [
+ # A far-future Date header is rejected and falls back to the authenticated timestamp.
+ ("future_date_rejected", "Mon, 1 Jan 2999 00:00:00 +0000", datetime(2025, 6, 10, 14, 30, tzinfo=UTC)),
+ # A plausible past Date header is kept as-is, not overridden by the timestamp.
+ ("valid_past_date_kept", "Wed, 1 Jan 2025 00:00:00 +0000", datetime(2025, 1, 1, 0, 0, tzinfo=UTC)),
+ ]
+ )
+ def test_parse_sent_at(self, _name: str, date_header: str, expected: datetime) -> None:
+ request = self.factory.post("/", {"Date": date_header, "timestamp": "1749565800"})
+
+ assert _parse_sent_at(request) == expected
diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.py
index 761053359d4c..de2bf683569e 100644
--- a/products/conversations/backend/api/tests/test_email_endpoints.py
+++ b/products/conversations/backend/api/tests/test_email_endpoints.py
@@ -1032,35 +1032,6 @@ class TestEmailInboundMultiConfig(BaseTest):
ticket = Ticket.objects.get(team=self.team)
assert ticket.email_config_id == config2.id
- @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)
- def test_customer_communication_channel_does_not_create_support_ticket(self, _mock_sig: MagicMock) -> None:
- config = EmailChannel.objects.create(
- team=self.team,
- kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
- owner=self.user,
- inbound_token="c0570a111",
- from_email="[email protected]",
- from_name="Customer success",
- domain="example.com",
- domain_verified=True,
- )
-
- response = self.client.post(
- "/api/conversations/v1/email/inbound",
- {
- "recipient": "[email protected]",
- "from": "[email protected]",
- "Message-Id": "<[email protected]>",
- "subject": "Account question",
- "stripped-text": "Can you help?",
- },
- )
-
- assert response.status_code == 200
- assert not Ticket.objects.filter(team=self.team).exists()
- assert not Comment.objects.filter(team=self.team).exists()
- assert EmailChannel.objects.get(id=config.id).kind == EmailChannelKind.CUSTOMER_COMMUNICATION
-
class TestEmailInboundContent(BaseTest):
def setUp(self):
diff --git a/products/conversations/backend/migrations/0061_emailchannelsetup_emailchannel_connection_status_and_more.py b/products/conversations/backend/migrations/0061_emailchannelsetup_emailchannel_connection_status_and_more.py
new file mode 100644
index 000000000000..6e4a792840b5
--- /dev/null
+++ b/products/conversations/backend/migrations/0061_emailchannelsetup_emailchannel_connection_status_and_more.py
@@ -0,0 +1,88 @@
+# Generated by Django 5.2.17 on 2026-08-12 20:47
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+import posthog.helpers.encrypted_fields
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("conversations", "0060_emailthread_emailthreadmessage_and_more"),
+ ("posthog", "1296_backfill_cimd_verification_token_url"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="EmailChannelSetup",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ (
+ "provider",
+ models.CharField(choices=[("google", "Google")], max_length=32),
+ ),
+ ("expires_at", models.DateTimeField()),
+ (
+ "confirmation_action",
+ posthog.helpers.encrypted_fields.EncryptedTextField(blank=True, null=True),
+ ),
+ (
+ "confirmation_message_id_hash",
+ models.CharField(blank=True, default="", max_length=64),
+ ),
+ (
+ "confirmation_received_at",
+ models.DateTimeField(blank=True, null=True),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "channel",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="setup",
+ to="conversations.emailchannel",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_conversations_email_channel_setup",
+ },
+ ),
+ migrations.AddField(
+ model_name="emailchannel",
+ name="connection_status",
+ field=models.CharField(
+ choices=[
+ ("pending_confirmation", "Pending confirmation"),
+ ("active", "Active"),
+ ("confirmation_expired", "Confirmation expired"),
+ ],
+ db_default="active",
+ default="active",
+ max_length=32,
+ ),
+ ),
+ migrations.AddField(
+ model_name="emailthreadmessage",
+ name="sender_authenticated",
+ field=models.BooleanField(db_default=False, default=False),
+ ),
+ ]
diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txt
index 743fd9571bf1..f913e76692c0 100644
--- a/products/conversations/backend/migrations/max_migration.txt
+++ b/products/conversations/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0060_emailthread_emailthreadmessage_and_more
+0061_emailchannelsetup_emailchannel_connection_status_and_more
diff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.py
index 8bbb53c2d243..b329eae615bd 100644
--- a/products/conversations/backend/models/__init__.py
+++ b/products/conversations/backend/models/__init__.py
@@ -1,5 +1,6 @@
from .assignment import TicketAssignment
from .constants import Channel, ChannelDetail, Priority, RuleType, Status
+from .email_channel_setup import EmailChannelSetup, EmailChannelSetupProvider
from .email_message_mapping import EmailMessageMapping
from .email_outbox_message import EmailOutboxMessage
from .email_thread import (
@@ -13,7 +14,7 @@ from .email_thread import (
from .github_comment_mapping import GithubCommentMapping
from .restore_token import ConversationRestoreToken
from .signing_secret import SigningSecret
-from .team_conversations_email_config import EmailChannel, EmailChannelKind
+from .team_conversations_email_config import EmailChannel, EmailChannelConnectionStatus, EmailChannelKind
from .team_conversations_slack_config import TeamConversationsSlackConfig
from .team_conversations_teams_channel_sync import TeamConversationsTeamsChannelSync
from .team_conversations_teams_config import TeamConversationsTeamsConfig
@@ -27,7 +28,10 @@ __all__ = [
"ChannelDetail",
"ConversationRestoreToken",
"EmailChannel",
+ "EmailChannelConnectionStatus",
"EmailChannelKind",
+ "EmailChannelSetup",
+ "EmailChannelSetupProvider",
"EmailMessageMapping",
"EmailOutboxMessage",
"EMAIL_THREAD_COMMENT_SCOPE",
diff --git a/products/conversations/backend/models/email_channel_setup.py b/products/conversations/backend/models/email_channel_setup.py
new file mode 100644
index 000000000000..c980644e07ab
--- /dev/null
+++ b/products/conversations/backend/models/email_channel_setup.py
@@ -0,0 +1,28 @@
+from django.db import models
+
+from posthog.helpers.encrypted_fields import EncryptedTextField
+from posthog.models.scoping.root_mixin import TeamScopedRootMixin
+from posthog.models.utils import UUIDModel
+
+
+class EmailChannelSetupProvider(models.TextChoices):
+ GOOGLE = "google", "Google"
+
+
+class EmailChannelSetup(TeamScopedRootMixin, UUIDModel):
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ channel = models.OneToOneField(
+ "conversations.EmailChannel",
+ on_delete=models.CASCADE,
+ related_name="setup",
+ )
+ provider = models.CharField(max_length=32, choices=EmailChannelSetupProvider.choices)
+ expires_at = models.DateTimeField()
+ confirmation_action = EncryptedTextField(null=True, blank=True)
+ confirmation_message_id_hash = models.CharField(max_length=64, default="", blank=True)
+ confirmation_received_at = models.DateTimeField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ db_table = "posthog_conversations_email_channel_setup"
diff --git a/products/conversations/backend/models/email_thread.py b/products/conversations/backend/models/email_thread.py
index fc7e387258fd..259144ffff8b 100644
--- a/products/conversations/backend/models/email_thread.py
+++ b/products/conversations/backend/models/email_thread.py
@@ -57,6 +57,7 @@ class EmailThreadMessage(TeamScopedRootMixin, UUIDModel):
sender_name = models.CharField(max_length=400, default="", blank=True)
to_recipients = models.JSONField(default=list, blank=True)
cc_recipients = models.JSONField(default=list, blank=True)
+ sender_authenticated = models.BooleanField(default=False, db_default=False)
direction = models.CharField(max_length=16, choices=EmailThreadMessageDirection.choices)
source_type = models.CharField(max_length=64)
source_id = models.CharField(max_length=512)
diff --git a/products/conversations/backend/models/team_conversations_email_config.py b/products/conversations/backend/models/team_conversations_email_config.py
index 38357fc94fa3..944bf0c162b6 100644
--- a/products/conversations/backend/models/team_conversations_email_config.py
+++ b/products/conversations/backend/models/team_conversations_email_config.py
@@ -12,6 +12,12 @@ class EmailChannelKind(models.TextChoices):
CUSTOMER_COMMUNICATION = "customer_communication", "Customer communication"
+class EmailChannelConnectionStatus(models.TextChoices):
+ PENDING_CONFIRMATION = "pending_confirmation", "Pending confirmation"
+ ACTIVE = "active", "Active"
+ CONFIRMATION_EXPIRED = "confirmation_expired", "Confirmation expired"
+
+
class EmailChannel(UUIDModel):
"""An inbound forwarding address and outbound sender identity for a team."""
@@ -30,6 +36,12 @@ class EmailChannel(UUIDModel):
db_constraint=False,
related_name="owned_conversations_email_channels",
)
+ connection_status = models.CharField(
+ max_length=32,
+ choices=EmailChannelConnectionStatus.choices,
+ default=EmailChannelConnectionStatus.ACTIVE,
+ db_default=EmailChannelConnectionStatus.ACTIVE,
+ )
# The random token keeps the team id out of the public forwarding address and supports rotation.
inbound_token = models.CharField(max_length=64, unique=True, db_index=True)
diff --git a/products/conversations/backend/services/email_channel_setup.py b/products/conversations/backend/services/email_channel_setup.py
new file mode 100644
index 000000000000..6196322766d6
--- /dev/null
+++ b/products/conversations/backend/services/email_channel_setup.py
@@ -0,0 +1,125 @@
+import re
+from hashlib import sha256
+from html import unescape
+from urllib.parse import urlsplit
+
+from django.utils import timezone
+
+from products.conversations.backend.models import (
+ EmailChannel,
+ EmailChannelConnectionStatus,
+ EmailChannelSetup,
+ EmailChannelSetupProvider,
+)
+from products.conversations.backend.services.email_thread_ingestion import ParsedInboundEmail
+
+_GOOGLE_FORWARDING_SENDER = "[email protected]"
+_GOOGLE_DKIM_DOMAIN = "google.com"
+_GOOGLE_CONFIRMATION_HOSTS = {"mail.google.com", "mail-settings.google.com"}
+_GOOGLE_CONFIRMATION_PATH_PREFIX = "/mail/vf-"
+_GOOGLE_FORWARDING_SUBJECT_RE = re.compile(
+ r"^(?:(?:\(#\d+\)\s*)?Gmail|\([^\r\n]{1,100}) Forwarding Confirmation\s*-\s*Receive Mail from\s+"
+ r"(?P<source>[^\s<>()]+@[^\s<>()]+)\)?\s*$",
+ re.IGNORECASE,
+)
+_HTTPS_URL_RE = re.compile(r"https://[^\s<>\"']+", re.IGNORECASE)
+
+
+def _google_source_email(email: ParsedInboundEmail) -> str | None:
+ match = _GOOGLE_FORWARDING_SUBJECT_RE.fullmatch(email.subject.strip())
+ if match is None:
+ return None
+ return match.group("source").lower()
+
+
+def _validated_google_action(email: ParsedInboundEmail) -> str | None:
+ candidates: set[str] = set()
+ for raw_candidate in _HTTPS_URL_RE.findall(f"{email.body_plain}\n{email.stripped_text}"):
+ candidate = unescape(raw_candidate).rstrip(".,);]}")
+ try:
+ parsed = urlsplit(candidate)
+ port = parsed.port
+ except ValueError:
+ continue
+ if (
+ parsed.scheme.lower() != "https"
+ or parsed.hostname is None
+ or parsed.hostname.rstrip(".").lower() not in _GOOGLE_CONFIRMATION_HOSTS
+ or parsed.username is not None
+ or parsed.password is not None
+ or port not in (None, 443)
+ or not parsed.path.startswith(_GOOGLE_CONFIRMATION_PATH_PREFIX)
+ ):
+ continue
+ candidates.add(candidate)
+ if len(candidates) != 1:
+ return None
+ return next(iter(candidates))
+
+
+def _is_google_authenticated(email: ParsedInboundEmail) -> bool:
+ return (
+ email.sender.email == _GOOGLE_FORWARDING_SENDER
+ and email.sender_authenticated
+ and email.dkim_passed
+ and set(email.dkim_signing_domains) == {_GOOGLE_DKIM_DOMAIN}
+ )
+
+
+def capture_google_forwarding_confirmation(
+ *,
+ team_id: int,
+ channel: EmailChannel,
+ email: ParsedInboundEmail,
+) -> bool:
+ if channel.connection_status != EmailChannelConnectionStatus.PENDING_CONFIRMATION:
+ return False
+
+ expected_capture_prefix = f"team-{channel.inbound_token}@"
+ if not email.capture_address.startswith(expected_capture_prefix):
+ return False
+
+ now = timezone.now()
+ setup = (
+ EmailChannelSetup.objects.for_team(team_id)
+ .filter(
+ channel_id=channel.id,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ )
+ .first()
+ )
+ if setup is None:
+ return False
+ if setup.expires_at <= now:
+ EmailChannelSetup.objects.for_team(team_id).filter(id=setup.id, expires_at__lte=now).delete()
+ EmailChannel.objects.filter(
+ id=channel.id,
+ team_id=team_id,
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ ).update(connection_status=EmailChannelConnectionStatus.CONFIRMATION_EXPIRED)
+ return False
+
+ if not _is_google_authenticated(email):
+ return False
+ if _google_source_email(email) != channel.from_email.lower():
+ return False
+ confirmation_action = _validated_google_action(email)
+ if confirmation_action is None:
+ return False
+
+ updated = (
+ EmailChannelSetup.objects.for_team(team_id)
+ .filter(
+ id=setup.id,
+ channel_id=channel.id,
+ channel__connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ expires_at__gt=now,
+ confirmation_action__isnull=True,
+ )
+ .update(
+ confirmation_action=confirmation_action,
+ confirmation_message_id_hash=sha256(email.message_id.encode()).hexdigest(),
+ confirmation_received_at=now,
+ )
+ )
+ return updated == 1
diff --git a/products/conversations/backend/services/email_thread_ingestion.py b/products/conversations/backend/services/email_thread_ingestion.py
new file mode 100644
index 000000000000..348bca3ec6bc
--- /dev/null
+++ b/products/conversations/backend/services/email_thread_ingestion.py
@@ -0,0 +1,278 @@
+from dataclasses import dataclass
+from datetime import datetime
+from hashlib import sha256
+from uuid import UUID
+
+from django.core.files.uploadedfile import UploadedFile
+from django.db import IntegrityError, transaction
+from django.db.models.functions import Lower
+
+from posthog.models.comment import Comment
+from posthog.models.organization import OrganizationMembership
+
+from products.conversations.backend.models import (
+ EMAIL_THREAD_COMMENT_SCOPE,
+ EmailChannel,
+ EmailThread,
+ EmailThreadMessage,
+ EmailThreadMessageDirection,
+ EmailThreadParticipant,
+ EmailThreadParticipantKind,
+)
+
+
+@dataclass(frozen=True, kw_only=True)
+class EmailAddress:
+ name: str
+ email: str
+
+ def as_dict(self) -> dict[str, str]:
+ return {"name": self.name, "email": self.email}
+
+
+@dataclass(frozen=True, kw_only=True)
+class ParsedInboundEmail:
+ message_id: str
+ in_reply_to: str | None
+ references: tuple[str, ...]
+ sent_at: datetime
+ sender: EmailAddress
+ to_recipients: tuple[EmailAddress, ...]
+ cc_recipients: tuple[EmailAddress, ...]
+ subject: str
+ body_plain: str
+ stripped_text: str
+ sender_authenticated: bool
+ dkim_passed: bool
+ dkim_signing_domains: tuple[str, ...]
+ capture_address: str
+ attachments: tuple[UploadedFile, ...]
+
+
+@dataclass(frozen=True, kw_only=True)
+class EmailThreadIngestionResult:
+ thread_id: UUID
+ message_id: UUID
+ created: bool
+
+
+def _mailgun_source_id(message_id: str) -> str:
+ if len(message_id) <= 512:
+ return message_id
+ return f"sha256:{sha256(message_id.encode()).hexdigest()}"
+
+
+def _find_existing_message(*, team_id: int, email: ParsedInboundEmail) -> EmailThreadMessage | None:
+ return (
+ EmailThreadMessage.objects.for_team(team_id)
+ .select_related("thread")
+ .filter(message_id=email.message_id)
+ .first()
+ )
+
+
+def _find_thread(*, team_id: int, email: ParsedInboundEmail) -> EmailThread | None:
+ message_candidates = tuple(
+ dict.fromkeys(candidate for candidate in (email.in_reply_to, *reversed(email.references)) if candidate)
+ )
+ if message_candidates:
+ messages_by_id = {
+ message.message_id: message.thread
+ for message in EmailThreadMessage.objects.for_team(team_id)
+ .select_related("thread")
+ .filter(message_id__in=message_candidates)
+ }
+ for candidate in message_candidates:
+ if candidate in messages_by_id:
+ return messages_by_id[candidate]
+
+ thread_key_candidates = tuple(
+ dict.fromkeys(
+ candidate for candidate in (email.message_id, email.in_reply_to, *reversed(email.references)) if candidate
+ )
+ )
+ threads_by_key = {
+ thread.canonical_thread_key: thread
+ for thread in EmailThread.objects.for_team(team_id).filter(canonical_thread_key__in=thread_key_candidates)
+ }
+ for candidate in thread_key_candidates:
+ if candidate in threads_by_key:
+ return threads_by_key[candidate]
+ return None
+
+
+def _get_or_create_thread(*, team_id: int, email: ParsedInboundEmail) -> EmailThread:
+ existing_thread = _find_thread(team_id=team_id, email=email)
+ if existing_thread is not None:
+ return existing_thread
+
+ canonical_thread_key = email.references[0] if email.references else email.in_reply_to or email.message_id
+ thread, _ = EmailThread.objects.for_team(team_id).get_or_create(
+ team_id=team_id,
+ canonical_thread_key=canonical_thread_key,
+ defaults={"subject": email.subject},
+ )
+ return thread
+
+
+def _upsert_participants(
+ *,
+ team_id: int,
+ thread: EmailThread,
+ channel: EmailChannel,
+ email: ParsedInboundEmail,
+) -> None:
+ owner = channel.owner
+ if owner is None:
+ raise ValueError("Customer communication channels require an owner")
+
+ addresses = [email.sender, *email.to_recipients, *email.cc_recipients]
+ addresses.append(EmailAddress(name=channel.from_name, email=channel.from_email.lower()))
+ if owner.email.lower() != channel.from_email.lower():
+ addresses.append(EmailAddress(name="", email=owner.email.lower()))
+
+ addresses_by_email: dict[str, EmailAddress] = {}
+ capture_address = email.capture_address.lower()
+ for address in addresses:
+ normalized_email = address.email.strip().lower()[:400]
+ if not normalized_email or normalized_email == capture_address:
+ continue
+ current = addresses_by_email.get(normalized_email)
+ if current is None or (not current.name and address.name):
+ addresses_by_email[normalized_email] = EmailAddress(name=address.name[:400], email=normalized_email)
+
+ organization_member_emails = set(
+ OrganizationMembership.objects.filter(
+ organization_id=channel.team.organization_id,
+ user__is_active=True,
+ )
+ .annotate(normalized_member_email=Lower("user__email"))
+ .filter(normalized_member_email__in=list(addresses_by_email))
+ .values_list("normalized_member_email", flat=True)
+ )
+ organization_member_emails.update({channel.from_email.lower(), owner.email.lower()})
+
+ for address in addresses_by_email.values():
+ kind = (
+ EmailThreadParticipantKind.INTERNAL
+ if address.email in organization_member_emails
+ else EmailThreadParticipantKind.CUSTOMER
+ )
+ participant, created = EmailThreadParticipant.objects.for_team(team_id).get_or_create(
+ team_id=team_id,
+ thread=thread,
+ email=address.email,
+ defaults={"display_name": address.name, "kind": kind},
+ )
+ if created:
+ continue
+
+ update_fields: list[str] = []
+ if address.name and participant.display_name != address.name:
+ participant.display_name = address.name
+ update_fields.append("display_name")
+ if kind == EmailThreadParticipantKind.INTERNAL and participant.kind != kind:
+ participant.kind = kind
+ update_fields.append("kind")
+ if update_fields:
+ participant.save(update_fields=[*update_fields, "updated_at"])
+
+
+def _message_content(*, thread: EmailThread, email: ParsedInboundEmail) -> str:
+ if thread.message_count > 0:
+ return email.stripped_text or email.body_plain
+ return email.body_plain or email.stripped_text
+
+
+def _update_thread_summary(*, thread: EmailThread, email: ParsedInboundEmail, content: str) -> None:
+ update_fields = ["message_count", "updated_at"]
+ thread.message_count += 1
+
+ if thread.first_message_at is None or email.sent_at < thread.first_message_at:
+ thread.first_message_at = email.sent_at
+ update_fields.append("first_message_at")
+
+ if thread.last_message_at is None or email.sent_at >= thread.last_message_at:
+ thread.last_message_at = email.sent_at
+ thread.preview = content[:500]
+ update_fields.extend(["last_message_at", "preview"])
+
+ if not thread.subject and email.subject:
+ thread.subject = email.subject
+ update_fields.append("subject")
+
+ thread.save(update_fields=update_fields)
+
+
+def _ingest_customer_email_once(
+ *,
+ team_id: int,
+ channel: EmailChannel,
+ email: ParsedInboundEmail,
+) -> EmailThreadIngestionResult:
+ existing_message = _find_existing_message(team_id=team_id, email=email)
+ if existing_message is not None:
+ return EmailThreadIngestionResult(
+ thread_id=existing_message.thread_id,
+ message_id=existing_message.id,
+ created=False,
+ )
+
+ thread = _get_or_create_thread(team_id=team_id, email=email)
+ thread = EmailThread.objects.for_team(team_id).select_for_update().get(id=thread.id)
+
+ existing_message = _find_existing_message(team_id=team_id, email=email)
+ if existing_message is not None:
+ return EmailThreadIngestionResult(
+ thread_id=existing_message.thread_id,
+ message_id=existing_message.id,
+ created=False,
+ )
+
+ content = _message_content(thread=thread, email=email)
+ comment = Comment.objects.create(
+ team_id=team_id,
+ scope=EMAIL_THREAD_COMMENT_SCOPE,
+ item_id=str(thread.id),
+ content=content,
+ )
+ message = EmailThreadMessage.objects.for_team(team_id).create(
+ team_id=team_id,
+ thread=thread,
+ comment=comment,
+ message_id=email.message_id,
+ in_reply_to=email.in_reply_to,
+ references=list(email.references),
+ sent_at=email.sent_at,
+ sender_email=email.sender.email,
+ sender_name=email.sender.name,
+ to_recipients=[recipient.as_dict() for recipient in email.to_recipients],
+ cc_recipients=[recipient.as_dict() for recipient in email.cc_recipients],
+ sender_authenticated=email.sender_authenticated,
+ direction=EmailThreadMessageDirection.INBOUND,
+ source_type="mailgun",
+ source_id=_mailgun_source_id(email.message_id),
+ )
+ _upsert_participants(team_id=team_id, thread=thread, channel=channel, email=email)
+ _update_thread_summary(thread=thread, email=email, content=content)
+ return EmailThreadIngestionResult(thread_id=thread.id, message_id=message.id, created=True)
+
+
+def ingest_customer_email(
+ *,
+ team_id: int,
+ channel: EmailChannel,
+ email: ParsedInboundEmail,
+) -> EmailThreadIngestionResult:
+ try:
+ with transaction.atomic():
+ return _ingest_customer_email_once(team_id=team_id, channel=channel, email=email)
+ except IntegrityError:
+ existing_message = _find_existing_message(team_id=team_id, email=email)
+ if existing_message is None:
+ raise
+ return EmailThreadIngestionResult(
+ thread_id=existing_message.thread_id,
+ message_id=existing_message.id,
+ created=False,
+ )
diff --git a/products/conversations/backend/tests/test_email_threads.py b/products/conversations/backend/tests/test_email_threads.py
index 467f7d207435..6157e7334f9d 100644
--- a/products/conversations/backend/tests/test_email_threads.py
+++ b/products/conversations/backend/tests/test_email_threads.py
@@ -8,9 +8,12 @@ from django.utils import timezone
from parameterized import parameterized
from posthog.models.comment import Comment
+from posthog.models.user import User
from products.conversations.backend.models import (
EMAIL_THREAD_COMMENT_SCOPE,
+ EmailChannel,
+ EmailChannelKind,
EmailThread,
EmailThreadMessage,
EmailThreadMessageDirection,
@@ -18,6 +21,11 @@ from products.conversations.backend.models import (
EmailThreadParticipantKind,
Ticket,
)
+from products.conversations.backend.services.email_thread_ingestion import (
+ EmailAddress,
+ ParsedInboundEmail,
+ _upsert_participants,
+)
from products.conversations.backend.services.email_threads import delete_email_thread
@@ -222,3 +230,45 @@ class TestEmailThreadPersistence(BaseTest):
assert not EmailThreadParticipant.objects.for_team(self.team.id).filter(thread_id=thread.id).exists()
assert not Comment.objects.filter(id__in=[message.comment_id, orphaned_content.id]).exists()
assert Comment.objects.filter(id=unrelated.id).exists()
+
+ def test_member_with_mixed_case_email_is_classified_internal(self) -> None:
+ # SCIM and invite flows store User.email verbatim, so a member can carry uppercase
+ # characters while parsed inbound addresses always arrive lowercased. The classification
+ # must still recognize them as internal rather than persist them as a customer.
+ member = User.objects.create_and_join(self.organization, "[email protected]", None)
+ User.objects.filter(id=member.id).update(email="[email protected]")
+
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="mixed-case-member-token",
+ from_email="[email protected]",
+ from_name="Support",
+ domain="example.com",
+ )
+ thread = self._create_thread()
+ email = ParsedInboundEmail(
+ message_id="<[email protected]>",
+ in_reply_to=None,
+ references=(),
+ sent_at=timezone.now(),
+ sender=EmailAddress(name="Customer", email="[email protected]"),
+ to_recipients=(EmailAddress(name="", email="[email protected]"),),
+ cc_recipients=(EmailAddress(name="Colleague", email="[email protected]"),),
+ subject="Quarterly planning",
+ body_plain="Hello",
+ stripped_text="Hello",
+ sender_authenticated=True,
+ dkim_passed=True,
+ dkim_signing_domains=("example.com",),
+ capture_address="[email protected]",
+ attachments=(),
+ )
+
+ _upsert_participants(team_id=self.team.id, thread=thread, channel=channel, email=email)
+
+ participant = EmailThreadParticipant.objects.for_team(self.team.id).get(
+ thread=thread, email="[email protected]"
+ )
+ assert participant.kind == EmailThreadParticipantKind.INTERNAL