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 outbound customer email (#82702)

Arthur Moreira de Deus3007edc8adc6
diff --git a/.test_quarantine.json b/.test_quarantine.json
index 4c2b065e9b6a..1a574dc0102b 100644
--- a/.test_quarantine.json
+++ b/.test_quarantine.json
@@ -1,16 +1,6 @@
{
"version": 1,
"entries": [
- {
- "id": "ee/clickhouse/queries/test/test_cohort_query.py::TestCohortQuery::test_cohort_filter_with_extra",
- "runner": "pytest",
- "reason": "ClickHouse 26.3.x drops UNION DISTINCT dedup when every branch has ORDER BY; fails until prod US upgrades to CH 26.6",
- "owner": "@team-feature-flags",
- "issue": "https://github.com/PostHog/posthog/pull/72896",
- "added": "2026-07-24",
- "expires": "2026-08-07",
- "mode": "run"
- },
{
"id": "playwright/e2e/product-analytics/dashboards.spec.ts::Dashboards Deleting an insight from dashboard redirects back",
"runner": "playwright",
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.py
index 327c014fa06e..86eda027cc2d 100644
--- a/products/conversations/backend/api/email_events.py
+++ b/products/conversations/backend/api/email_events.py
@@ -1,4 +1,4 @@
-"""Inbound email webhook endpoint for Mailgun routes."""
+"""Email webhook endpoints for Mailgun routes."""
import re
import json
@@ -28,6 +28,7 @@ from products.conversations.backend.models import (
EmailChannelConnectionStatus,
EmailChannelKind,
EmailMessageMapping,
+ EmailThreadMessageDirection,
Status,
)
from products.conversations.backend.models.ticket import Ticket
@@ -44,18 +45,25 @@ from products.conversations.backend.services.email_channel_setup import (
)
from products.conversations.backend.services.email_thread_ingestion import (
EmailAddress,
- ParsedInboundEmail,
+ ParsedEmail,
ingest_customer_email,
)
-from products.conversations.backend.services.region_routing import is_primary_region, proxy_to_secondary_region
+from products.conversations.backend.services.region_routing import (
+ is_primary_region,
+ proxy_to_secondary_region,
+ request_secondary_region_status,
+)
logger = structlog.get_logger(__name__)
INBOUND_TOKEN_PATTERN = re.compile(r"^team-([a-f0-9]+)@")
+OUTBOUND_CAPTURE_LOCAL_PART = "sent"
+OUTBOUND_SENDER_LOOKUP_QUERY_PARAM = "sender_lookup"
_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]+>")
_FORWARDING_CHALLENGE_RE = re.compile(rf"{re.escape(FORWARDING_CHALLENGE_MARKER)}(?P<token>[A-Za-z0-9_.:-]{{1,1000}})")
+_DKIM_DOMAIN_RE = re.compile(r"(?:^|;)\s*d\s*=\s*([^;\s]+)", re.IGNORECASE)
MAX_EMAIL_BODY_LENGTH = 50_000
MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024 # 10 MB per file
MAX_ATTACHMENTS = 20
@@ -255,29 +263,38 @@ def _recover_dmarc_rewritten_sender(
return sender_email, sender_name
+def _dkim_aligned_with_sender(request: HttpRequest, sender_domain: str) -> bool:
+ if not _mailgun_authentication_passed(request, "X-Mailgun-Dkim-Check-Result"):
+ return False
+
+ signing_domains: list[str] = []
+ for signature in _message_header_values(request, "DKIM-Signature"):
+ match = _DKIM_DOMAIN_RE.search(signature)
+ if match:
+ signing_domains.append(match.group(1).rstrip(".").lower())
+ return bool(signing_domains) and all(domain == sender_domain for domain in signing_domains)
+
+
def _sender_authenticated(request: HttpRequest, sender_email: str) -> bool:
- """Verify the From header domain is authenticated before trusting it for identity.
-
- We require SPF pass + envelope-to-From domain alignment:
- - SPF pass means the sending IP is authorized by the envelope sender's
- domain DNS (X-Mailgun-Spf). An attacker can't pass SPF for posthog.com
- without controlling posthog.com's DNS records.
- - Domain alignment means the envelope sender (MAIL FROM) domain matches
- the From header domain, preventing an attacker from passing SPF on
- evil.com while forging From: [email protected].
-
- DKIM alone is insufficient — Mailgun's X-Mailgun-Dkim-Check-Result only
- confirms a valid signature exists without reporting which domain signed it.
- An attacker signing with evil.com's key but forging From: [email protected]
- would still get DKIM Pass.
+ """Verify the From header domain before trusting it for identity.
+
+ Mailgun SPF checks can fail for legitimate senders, so aligned DKIM is accepted as a fallback.
+ A DKIM pass is trusted only when every signature uses the From domain, which prevents an unrelated
+ valid signature from authenticating a forged From address.
"""
- spf_passed = _mailgun_authentication_passed(request, "X-Mailgun-Spf")
- if not spf_passed:
- return False
envelope_sender = request.POST.get("sender", "")
envelope_domain = envelope_sender.rsplit("@", 1)[-1].lower() if "@" in envelope_sender else ""
from_domain = sender_email.rsplit("@", 1)[-1].lower() if "@" in sender_email else ""
- return bool(envelope_domain and from_domain and envelope_domain == from_domain)
+ if not envelope_domain or not from_domain or envelope_domain != from_domain:
+ return False
+
+ spf_passed = _mailgun_authentication_passed(request, "X-Mailgun-Spf")
+ return spf_passed or _dkim_aligned_with_sender(request, from_domain)
+
+
+def _outbound_sender_authenticated(request: HttpRequest, sender_email: str) -> bool:
+ _, envelope_sender = parseaddr(request.POST.get("sender", ""))
+ return envelope_sender.strip().lower() == sender_email.lower() and _sender_authenticated(request, sender_email)
def _parse_message_ids(value: str) -> tuple[str, ...]:
@@ -398,7 +415,7 @@ def _parse_sent_at(request: HttpRequest) -> datetime:
return now
-def _parse_inbound_email(request: HttpRequest, config: EmailChannel) -> ParsedInboundEmail | None:
+def _parse_inbound_email(request: HttpRequest, config: EmailChannel) -> ParsedEmail | None:
message_ids = _parse_message_ids(request.POST.get("Message-Id", ""))
if not message_ids:
return None
@@ -431,7 +448,7 @@ def _parse_inbound_email(request: HttpRequest, config: EmailChannel) -> ParsedIn
continue
attachments.append(uploaded_file)
- return ParsedInboundEmail(
+ return ParsedEmail(
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", "")),
@@ -498,7 +515,7 @@ def _process_support_email(
*,
config: EmailChannel,
inbound_token: str,
- email: ParsedInboundEmail,
+ email: ParsedEmail,
) -> HttpResponse:
team = config.team
settings_dict = team.conversations_settings or {}
@@ -628,6 +645,128 @@ def _process_support_email(
return HttpResponse(status=200)
+def _is_outbound_capture_recipient(recipient: str) -> bool:
+ local_part, separator, domain = recipient.strip().lower().partition("@")
+ return local_part == OUTBOUND_CAPTURE_LOCAL_PART and bool(separator and domain)
+
+
+def _has_external_recipient(*, config: EmailChannel, email: ParsedEmail) -> bool:
+ recipient_emails = {
+ recipient.email
+ for recipient in (*email.to_recipients, *email.cc_recipients)
+ if recipient.email and recipient.email != email.capture_address
+ }
+ if not recipient_emails:
+ return False
+
+ internal_emails = {
+ member_email.lower()
+ for member_email in OrganizationMembership.objects.filter(
+ organization_id=config.team.organization_id,
+ user__email__in=recipient_emails,
+ user__is_active=True,
+ ).values_list("user__email", flat=True)
+ }
+ internal_emails.add(config.from_email.lower())
+ if config.owner is not None:
+ internal_emails.add(config.owner.email.lower())
+ return bool(recipient_emails - internal_emails)
+
+
+@csrf_exempt
+def email_outbound_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_outbound_invalid_signature")
+ return HttpResponse("Invalid signature", status=403)
+
+ recipient = request.POST.get("recipient", "")
+ if not _is_outbound_capture_recipient(recipient):
+ logger.warning("email_outbound_invalid_recipient", recipient=recipient)
+ return HttpResponse("Invalid recipient", status=400)
+
+ _, sender_email = parseaddr(request.POST.get("from", ""))
+ if not sender_email:
+ sender_email = request.POST.get("sender", "")
+ sender_email = sender_email.strip().lower()[:400]
+ if not sender_email or not _outbound_sender_authenticated(request, sender_email):
+ logger.warning("email_outbound_unauthenticated_sender", sender_email=sender_email)
+ return HttpResponse(status=200)
+
+ config = (
+ EmailChannel.objects.select_related("team", "owner")
+ .filter(
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ connection_status=EmailChannelConnectionStatus.ACTIVE,
+ from_email__iexact=sender_email,
+ )
+ .first()
+ )
+ lookup_only = request.GET.get(OUTBOUND_SENDER_LOOKUP_QUERY_PARAM) == "1"
+ if config is None:
+ if lookup_only:
+ return HttpResponse(status=404)
+ if is_primary_region(request):
+ success = proxy_to_secondary_region(request, log_prefix="email_outbound", timeout=10)
+ return HttpResponse(status=200 if success else 502)
+ logger.info("email_outbound_unknown_sender", sender_email=sender_email)
+ return HttpResponse(status=200)
+
+ if lookup_only:
+ return HttpResponse(status=204)
+
+ if is_primary_region(request):
+ secondary_status = request_secondary_region_status(
+ request,
+ log_prefix="email_outbound_sender_lookup",
+ timeout=10,
+ query_params={OUTBOUND_SENDER_LOOKUP_QUERY_PARAM: "1"},
+ accepted_statuses=frozenset({404}),
+ )
+ if secondary_status is None or secondary_status >= 500:
+ return HttpResponse(status=502)
+ if secondary_status == 204:
+ logger.error(
+ "email_outbound_sender_region_ambiguous",
+ sender_email=sender_email,
+ team_id=config.team_id,
+ config_id=str(config.id),
+ )
+ return HttpResponse(status=200)
+ if secondary_status != 404:
+ return HttpResponse(status=502)
+
+ email = _parse_inbound_email(request, config)
+ if email is None:
+ logger.warning("email_outbound_no_message_id", team_id=config.team_id)
+ return HttpResponse(status=200)
+
+ if not _has_external_recipient(config=config, email=email):
+ logger.info("email_outbound_internal_only", team_id=config.team_id, config_id=str(config.id))
+ return HttpResponse(status=200)
+
+ result = ingest_customer_email(
+ team_id=config.team_id,
+ channel=config,
+ email=email,
+ direction=EmailThreadMessageDirection.OUTBOUND,
+ )
+ logger.info(
+ "customer_email_outbound_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)
+
+
@csrf_exempt
def email_inbound_handler(request: HttpRequest) -> HttpResponse:
if request.method != "POST":
@@ -693,7 +832,12 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
return HttpResponse(status=200)
try:
- result = ingest_customer_email(team_id=config.team_id, channel=config, email=email)
+ result = ingest_customer_email(
+ team_id=config.team_id,
+ channel=config,
+ email=email,
+ direction=EmailThreadMessageDirection.INBOUND,
+ )
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.
@@ -715,3 +859,10 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:
return HttpResponse(status=200)
return _process_support_email(config=config, inbound_token=inbound_token, email=email)
+
+
+@csrf_exempt
+def email_capture_handler(request: HttpRequest) -> HttpResponse:
+ if _is_outbound_capture_recipient(request.POST.get("recipient", "")):
+ return email_outbound_handler(request)
+ return email_inbound_handler(request)
diff --git a/products/conversations/backend/api/tests/test_customer_email_ingestion.py b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
index 39a7b8a4f972..4e99d1a78792 100644
--- a/products/conversations/backend/api/tests/test_customer_email_ingestion.py
+++ b/products/conversations/backend/api/tests/test_customer_email_ingestion.py
@@ -7,6 +7,7 @@ from freezegun import freeze_time
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
+from django.apps import apps
from django.test import Client, RequestFactory, SimpleTestCase
from django.utils import timezone
@@ -34,6 +35,7 @@ from products.conversations.backend.models import (
EmailThread,
EmailThreadAccountLink,
EmailThreadMessage,
+ EmailThreadMessageDirection,
Ticket,
)
from products.conversations.backend.services.email_channel_setup import (
@@ -41,6 +43,7 @@ from products.conversations.backend.services.email_channel_setup import (
FORWARDING_CHALLENGE_MARKER,
create_forwarding_challenge,
)
+from products.customer_analytics.backend.facade.email_matching import recalculate_email_thread_links
class TestCustomerEmailIngestion(BaseTest):
@@ -89,6 +92,42 @@ class TestCustomerEmailIngestion(BaseTest):
data.update(overrides)
return self.client.post("/api/conversations/v1/email/inbound", data)
+ def _post_outbound_email(
+ self,
+ *,
+ message_id: str,
+ lookup_only: str = "",
+ **overrides: str,
+ ):
+ data = {
+ "token": "webhook-token",
+ "timestamp": "1749565800",
+ "signature": "webhook-signature",
+ "recipient": "[email protected]",
+ "from": "Customer success <[email protected]>",
+ "sender": "[email protected]",
+ "To": "Prospect <[email protected]>",
+ "Message-Id": message_id,
+ "Date": "Tue, 10 Jun 2025 14:00:00 +0000",
+ "subject": "Account update",
+ "stripped-text": "Here is your account update.",
+ "body-plain": "Here is your account update.",
+ "message-headers": json.dumps(
+ [
+ ["X-Mailgun-Spf", "Fail"],
+ ["X-Mailgun-Dkim-Check-Result", "Pass"],
+ ["DKIM-Signature", "v=1; a=rsa-sha256; d=example.com; s=mail"],
+ ]
+ ),
+ }
+ data.update(overrides)
+ endpoint = (
+ "/api/conversations/v1/email/capture?sender_lookup=1"
+ if lookup_only == "1"
+ else "/api/conversations/v1/email/capture"
+ )
+ return self.client.post(endpoint, data)
+
def _start_google_setup(self, *, expires_at=None) -> EmailChannelSetup:
self.channel.connection_status = EmailChannelConnectionStatus.PENDING_CONFIRMATION
self.channel.save(update_fields=["connection_status"])
@@ -263,7 +302,13 @@ class TestCustomerEmailIngestion(BaseTest):
@parameterized.expand(
[
- ("missing_spf", {"X-Mailgun-Spf": ""}),
+ (
+ "failed_spf_and_dkim",
+ {
+ "X-Mailgun-Spf": "fail",
+ "X-Mailgun-Dkim-Check-Result": "fail",
+ },
+ ),
("wrong_source", {"subject": "Gmail Forwarding Confirmation - Receive Mail from [email protected]"}),
(
"wrong_dkim_domain",
@@ -403,6 +448,172 @@ class TestCustomerEmailIngestion(BaseTest):
assert EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread).count() == 1
assert not EmailThreadAccountLink.objects.for_team(self.team.id).exists()
+ def test_outbound_message_is_recovered_when_a_later_reply_matches_an_account(self) -> None:
+ outbound_message_id = "<[email protected]>"
+ outbound_response = self._post_outbound_email(message_id=outbound_message_id)
+
+ assert outbound_response.status_code == 200
+ thread = EmailThread.objects.for_team(self.team.id).get()
+ assert not EmailThreadAccountLink.objects.for_team(self.team.id).filter(thread=thread).exists()
+
+ account_model = apps.get_model("customer_analytics", "Account")
+ account = account_model.objects.for_team(self.team.id).create(
+ team=self.team,
+ name="Future account",
+ external_id="future-account",
+ _properties={"known_emails": ["[email protected]"]},
+ )
+ reply_response = self._post_email(
+ message_id="<[email protected]>",
+ **{
+ "from": "Prospect <[email protected]>",
+ "sender": "[email protected]",
+ "To": "Customer success <[email protected]>",
+ "In-Reply-To": outbound_message_id,
+ "Date": "Tue, 10 Jun 2025 15:00:00 +0000",
+ "body-plain": "Thanks for the update.",
+ "stripped-text": "Thanks for the update.",
+ "X-Mailgun-Spf": "pass",
+ },
+ )
+
+ assert reply_response.status_code == 200
+ recalculate_email_thread_links(self.team.id, thread_ids=[str(thread.id)])
+ thread.refresh_from_db()
+ messages = list(EmailThreadMessage.objects.for_team(self.team.id).filter(thread=thread))
+ assert thread.message_count == 2
+ assert [message.direction for message in messages] == [
+ EmailThreadMessageDirection.OUTBOUND,
+ EmailThreadMessageDirection.INBOUND,
+ ]
+ assert messages[0].sender_email == "[email protected]"
+ assert messages[0].sender_authenticated is True
+ assert messages[1].in_reply_to == outbound_message_id
+ link = EmailThreadAccountLink.objects.for_team(self.team.id).get(thread=thread)
+ assert link.account_id == str(account.id)
+ assert not Ticket.objects.filter(team=self.team).exists()
+ assert not EmailOutboxMessage.objects.filter(team=self.team).exists()
+
+ @parameterized.expand(
+ [
+ ("different_envelope", {"sender": "[email protected]"}),
+ (
+ "unaligned_dkim",
+ {
+ "message-headers": json.dumps(
+ [
+ ["X-Mailgun-Spf", "Fail"],
+ ["X-Mailgun-Dkim-Check-Result", "Pass"],
+ ["DKIM-Signature", "v=1; a=rsa-sha256; d=attacker.example; s=mail"],
+ ]
+ )
+ },
+ ),
+ (
+ "conflicting_authentication_results",
+ {
+ "message-headers": json.dumps(
+ [
+ ["X-Mailgun-Spf", "Fail"],
+ ["X-Mailgun-Spf", "Pass"],
+ ["X-Mailgun-Dkim-Check-Result", "Fail"],
+ ["X-Mailgun-Dkim-Check-Result", "Pass"],
+ ["DKIM-Signature", "v=1; a=rsa-sha256; d=example.com; s=mail"],
+ ]
+ )
+ },
+ ),
+ ]
+ )
+ def test_outbound_capture_rejects_an_unauthenticated_sender(self, _name: str, overrides: dict[str, str]) -> None:
+ response = self._post_outbound_email(
+ message_id=f"<spoofed-{_name}@customer-success.example>",
+ **overrides,
+ )
+
+ assert response.status_code == 200
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
+ @parameterized.expand(
+ [
+ ("secondary_absent", 404, 200, True),
+ ("sender_in_both_regions", 204, 200, False),
+ ("secondary_unavailable", None, 502, False),
+ ("secondary_error", 500, 502, False),
+ ]
+ )
+ @patch("products.conversations.backend.api.email_events.request_secondary_region_status")
+ @patch("products.conversations.backend.api.email_events.is_primary_region", return_value=True)
+ def test_primary_region_checks_secondary_before_ingesting(
+ self,
+ _name: str,
+ secondary_status: int | None,
+ expected_status: int,
+ expected_ingestion: bool,
+ _mock_primary: MagicMock,
+ mock_secondary_status: MagicMock,
+ ) -> None:
+ mock_secondary_status.return_value = secondary_status
+
+ response = self._post_outbound_email(message_id=f"<region-{_name}@example.com>")
+
+ assert response.status_code == expected_status
+ assert EmailThread.objects.for_team(self.team.id).exists() is expected_ingestion
+
+ @parameterized.expand(
+ [
+ ("active", EmailChannelConnectionStatus.ACTIVE, 204),
+ ("pending_confirmation", EmailChannelConnectionStatus.PENDING_CONFIRMATION, 404),
+ ("confirmation_expired", EmailChannelConnectionStatus.CONFIRMATION_EXPIRED, 404),
+ ]
+ )
+ def test_outbound_sender_lookup_returns_only_active_channels(
+ self, _name: str, connection_status: EmailChannelConnectionStatus, expected_status: int
+ ) -> None:
+ self.channel.connection_status = connection_status
+ self.channel.save(update_fields=["connection_status"])
+
+ response = self._post_outbound_email(
+ message_id=f"<lookup-{_name}@customer-success.example>",
+ lookup_only="1",
+ )
+
+ assert response.status_code == expected_status
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
+ @parameterized.expand(
+ [
+ ("pending_confirmation", EmailChannelConnectionStatus.PENDING_CONFIRMATION),
+ ("confirmation_expired", EmailChannelConnectionStatus.CONFIRMATION_EXPIRED),
+ ]
+ )
+ def test_outbound_capture_skips_non_active_channels(
+ self, _name: str, connection_status: EmailChannelConnectionStatus
+ ) -> None:
+ self.channel.connection_status = connection_status
+ self.channel.save(update_fields=["connection_status"])
+
+ response = self._post_outbound_email(message_id=f"<outbound-{_name}@customer-success.example>")
+
+ assert response.status_code == 200
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
+ def test_outbound_capture_drops_internal_only_messages(self) -> None:
+ colleague = User.objects.create(email="[email protected]", current_team=self.team)
+ OrganizationMembership.objects.create(
+ organization=self.organization,
+ user=colleague,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+
+ response = self._post_outbound_email(
+ message_id="<[email protected]>",
+ To="Colleague <[email protected]>",
+ )
+
+ assert response.status_code == 200
+ assert not EmailThread.objects.for_team(self.team.id).exists()
+
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)
diff --git a/products/conversations/backend/api/urls.py b/products/conversations/backend/api/urls.py
index b4a8147414f2..aed75d0ea100 100644
--- a/products/conversations/backend/api/urls.py
+++ b/products/conversations/backend/api/urls.py
@@ -2,7 +2,7 @@
from django.urls import path, re_path
-from .email_events import email_inbound_handler
+from .email_events import email_capture_handler, email_inbound_handler, email_outbound_handler
from .email_settings import (
EmailConfirmForwardingView,
EmailConnectView,
@@ -56,7 +56,9 @@ urlpatterns = [
re_path(r"^v1/teams/install/?$", TeamsInstallAppView.as_view(), name="teams-install"),
re_path(r"^v1/teams/select-channel/?$", TeamsSelectChannelView.as_view(), name="teams-select-channel"),
# Email channel
+ re_path(r"^v1/email/capture/?$", email_capture_handler, name="email-capture"),
re_path(r"^v1/email/inbound/?$", email_inbound_handler, name="email-inbound"),
+ re_path(r"^v1/email/outbound/?$", email_outbound_handler, name="email-outbound"),
re_path(r"^v1/email/status/?$", EmailStatusView.as_view(), name="email-status"),
re_path(r"^v1/email/connect/?$", EmailConnectView.as_view(), name="email-connect"),
re_path(
diff --git a/products/conversations/backend/services/email_channel_setup.py b/products/conversations/backend/services/email_channel_setup.py
index 93c22d9e257b..d8d010e0d844 100644
--- a/products/conversations/backend/services/email_channel_setup.py
+++ b/products/conversations/backend/services/email_channel_setup.py
@@ -19,7 +19,7 @@ from products.conversations.backend.models import (
EmailChannelSetup,
EmailChannelSetupProvider,
)
-from products.conversations.backend.services.email_thread_ingestion import ParsedInboundEmail
+from products.conversations.backend.services.email_thread_ingestion import ParsedEmail
_GOOGLE_FORWARDING_SENDER = "[email protected]"
_GOOGLE_DKIM_DOMAIN = "google.com"
@@ -196,14 +196,14 @@ def process_forwarding_challenges(
return ForwardingChallengeResult.CONSUMED if saw_bound_challenge else ForwardingChallengeResult.NOT_CHALLENGE
-def _google_source_email(email: ParsedInboundEmail) -> str | None:
+def _google_source_email(email: ParsedEmail) -> 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:
+def _validated_google_action(email: ParsedEmail) -> 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(".,);]}")
@@ -228,7 +228,7 @@ def _validated_google_action(email: ParsedInboundEmail) -> str | None:
return next(iter(candidates))
-def _is_google_authenticated(email: ParsedInboundEmail) -> bool:
+def _is_google_authenticated(email: ParsedEmail) -> bool:
return (
email.sender.email == _GOOGLE_FORWARDING_SENDER
and email.sender_authenticated
@@ -241,7 +241,7 @@ def capture_google_forwarding_confirmation(
*,
team_id: int,
channel: EmailChannel,
- email: ParsedInboundEmail,
+ email: ParsedEmail,
) -> bool:
if channel.connection_status != EmailChannelConnectionStatus.PENDING_CONFIRMATION:
return False
diff --git a/products/conversations/backend/services/email_thread_ingestion.py b/products/conversations/backend/services/email_thread_ingestion.py
index 1d1f585b2cdb..dd829cee978c 100644
--- a/products/conversations/backend/services/email_thread_ingestion.py
+++ b/products/conversations/backend/services/email_thread_ingestion.py
@@ -34,7 +34,7 @@ class EmailAddress:
@dataclass(frozen=True, kw_only=True)
-class ParsedInboundEmail:
+class ParsedEmail:
message_id: str
in_reply_to: str | None
references: tuple[str, ...]
@@ -66,7 +66,7 @@ def _mailgun_source_id(message_id: str) -> str:
return f"sha256:{sha256(message_id.encode()).hexdigest()}"
-def _find_existing_message(*, team_id: int, email: ParsedInboundEmail) -> EmailThreadMessage | None:
+def _find_existing_message(*, team_id: int, email: ParsedEmail) -> EmailThreadMessage | None:
return (
EmailThreadMessage.objects.for_team(team_id)
.select_related("thread")
@@ -75,7 +75,7 @@ def _find_existing_message(*, team_id: int, email: ParsedInboundEmail) -> EmailT
)
-def _find_thread(*, team_id: int, email: ParsedInboundEmail) -> EmailThread | None:
+def _find_thread(*, team_id: int, email: ParsedEmail) -> EmailThread | None:
message_candidates = tuple(
dict.fromkeys(candidate for candidate in (email.in_reply_to, *reversed(email.references)) if candidate)
)
@@ -105,7 +105,7 @@ def _find_thread(*, team_id: int, email: ParsedInboundEmail) -> EmailThread | No
return None
-def _get_or_create_thread(*, team_id: int, email: ParsedInboundEmail) -> EmailThread:
+def _get_or_create_thread(*, team_id: int, email: ParsedEmail) -> EmailThread:
existing_thread = _find_thread(team_id=team_id, email=email)
if existing_thread is not None:
return existing_thread
@@ -124,7 +124,7 @@ def _upsert_participants(
team_id: int,
thread: EmailThread,
channel: EmailChannel,
- email: ParsedInboundEmail,
+ email: ParsedEmail,
) -> None:
owner = channel.owner
if owner is None:
@@ -182,13 +182,13 @@ def _upsert_participants(
participant.save(update_fields=[*update_fields, "updated_at"])
-def _message_content(*, thread: EmailThread, email: ParsedInboundEmail) -> str:
+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
-def _update_thread_summary(*, thread: EmailThread, email: ParsedInboundEmail, content: str) -> None:
+def _update_thread_summary(*, thread: EmailThread, email: ParsedEmail, content: str) -> None:
update_fields = ["message_count", "updated_at"]
thread.message_count += 1
@@ -212,7 +212,8 @@ def _ingest_customer_email_once(
*,
team_id: int,
channel: EmailChannel,
- email: ParsedInboundEmail,
+ email: ParsedEmail,
+ direction: EmailThreadMessageDirection,
) -> EmailThreadIngestionResult:
existing_message = _find_existing_message(team_id=team_id, email=email)
if existing_message is not None:
@@ -253,7 +254,7 @@ def _ingest_customer_email_once(
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,
+ direction=direction,
source_type="mailgun",
source_id=_mailgun_source_id(email.message_id),
)
@@ -266,11 +267,17 @@ def ingest_customer_email(
*,
team_id: int,
channel: EmailChannel,
- email: ParsedInboundEmail,
+ email: ParsedEmail,
+ direction: EmailThreadMessageDirection,
) -> EmailThreadIngestionResult:
try:
with transaction.atomic():
- result = _ingest_customer_email_once(team_id=team_id, channel=channel, email=email)
+ result = _ingest_customer_email_once(
+ team_id=team_id,
+ channel=channel,
+ email=email,
+ direction=direction,
+ )
except IntegrityError:
existing_message = _find_existing_message(team_id=team_id, email=email)
if existing_message is None:
diff --git a/products/conversations/backend/services/region_routing.py b/products/conversations/backend/services/region_routing.py
index d9013d05c2a7..9765ba7e4be0 100644
--- a/products/conversations/backend/services/region_routing.py
+++ b/products/conversations/backend/services/region_routing.py
@@ -56,11 +56,14 @@ def _build_proxy_kwargs(request: HttpRequest, headers: dict[str, str]) -> dict:
return {"data": data, "files": files, "headers": cleaned_headers}
-def proxy_to_secondary_region(request: HttpRequest, *, log_prefix: str, timeout: int = 3) -> bool:
- """Forward an incoming webhook to the secondary region.
-
- Returns True if the proxy request succeeded (2xx), False otherwise.
- """
+def request_secondary_region_status(
+ request: HttpRequest,
+ *,
+ log_prefix: str,
+ timeout: int = 3,
+ query_params: dict[str, str] | None = None,
+ accepted_statuses: frozenset[int] = frozenset(),
+) -> int | None:
parsed_url = urlparse(request.build_absolute_uri())
target_url = urlunparse(parsed_url._replace(netloc=SECONDARY_REGION_DOMAIN))
headers = {key: value for key, value in request.headers.items() if key.lower() != "host"}
@@ -70,11 +73,11 @@ def proxy_to_secondary_region(request: HttpRequest, *, log_prefix: str, timeout:
response = requests.request(
method=request.method or "POST",
url=target_url,
- params=dict(request.GET.lists()) if request.GET else None,
+ params=query_params if query_params is not None else dict(request.GET.lists()) if request.GET else None,
timeout=timeout,
**proxy_kwargs,
)
- if response.ok:
+ if response.ok or response.status_code in accepted_statuses:
logger.info(
f"{log_prefix}_proxy_to_secondary_region",
target_url=target_url,
@@ -86,11 +89,20 @@ def proxy_to_secondary_region(request: HttpRequest, *, log_prefix: str, timeout:
target_url=target_url,
status_code=response.status_code,
)
- return response.ok
+ return response.status_code
except RequestException as exc:
logger.exception(
f"{log_prefix}_proxy_to_secondary_region_failed",
error=str(exc),
target_url=target_url,
)
- return False
+ return None
+
+
+def proxy_to_secondary_region(request: HttpRequest, *, log_prefix: str, timeout: int = 3) -> bool:
+ """Forward an incoming webhook to the secondary region.
+
+ Returns True if the proxy request succeeded (2xx), False otherwise.
+ """
+ status_code = request_secondary_region_status(request, log_prefix=log_prefix, timeout=timeout)
+ return status_code is not None and 200 <= status_code < 300
diff --git a/products/conversations/backend/tests/test_email_threads.py b/products/conversations/backend/tests/test_email_threads.py
index 3eea243cc040..6d14328cf4cb 100644
--- a/products/conversations/backend/tests/test_email_threads.py
+++ b/products/conversations/backend/tests/test_email_threads.py
@@ -24,7 +24,7 @@ from products.conversations.backend.models import (
)
from products.conversations.backend.services.email_thread_ingestion import (
EmailAddress,
- ParsedInboundEmail,
+ ParsedEmail,
_upsert_participants,
)
from products.conversations.backend.services.email_threads import delete_email_thread
@@ -257,7 +257,7 @@ class TestEmailThreadPersistence(BaseTest):
domain="example.com",
)
thread = self._create_thread()
- email = ParsedInboundEmail(
+ email = ParsedEmail(
message_id="<[email protected]>",
in_reply_to=None,
references=(),