: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(conversations): keep To recipients on email tickets (#71527)
Alex V5da092dd63f9
diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.pyindex c2caddff21c9..7ad82caf31b9 100644--- a/products/conversations/backend/api/email_events.py+++ b/products/conversations/backend/api/email_events.py@@ -248,6 +248,34 @@ def _sender_authenticated(request: HttpRequest, sender_email: str) -> bool:return bool(envelope_domain and from_domain and envelope_domain == from_domain)+def _collect_participants(+ to_header: str,+ cc_header: str,+ inbound_token: str,+ channel_email: str,+ sender_email: str,+) -> list[str]:+ """Collect the other people on the thread from the To + Cc headers.++ Excludes the support inbox itself (the Mailgun team-<token>@ inbound address+ and the channel's own from_email) and the sender, since none of those are+ "other participants" — they're the mailbox we received on, or the person we+ reply back to. The result is what we keep CC'd on outbound replies, so a+ direct recipient (someone in To with the support address only CC'd) stays on+ the thread instead of being dropped.+ """+ 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()+ if not low or low in excluded or low.startswith(team_inbound_address):+ continue+ if low not in participants:+ participants.append(low)+ return participants++def _resolve_team_member(email: str, team: Team) -> User | None:"""Match a sender email to a PostHog user within the team's organization."""if not email:@@ -329,16 +357,16 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:# 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 CC recipients- cc_header = request.POST.get("Cc", "")- cc_list: list[str] = []- if cc_header:- team_inbound_address = f"team-{inbound_token}@"- cc_list = [- addr.lower()- for _name, addr in getaddresses([cc_header])- if addr and not addr.lower().startswith(team_inbound_address)- ]+ # 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.+ cc_list = _collect_participants(+ to_header=request.POST.get("To", ""),+ cc_header=request.POST.get("Cc", ""),+ inbound_token=inbound_token,+ channel_email=config.from_email,+ sender_email=sender_email,+ )# 7. Get content (stripped by Mailgun to remove quotes/signatures)content = (request.POST.get("stripped-text", "") or request.POST.get("body-plain", ""))[:MAX_EMAIL_BODY_LENGTH]@@ -417,6 +445,11 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:)if existing_ticket:+ # The requester is already the reply target (to=email_from); when another+ # participant reply-alls, the requester shows up in their To/Cc and must not+ # be folded into cc_participants or replies would deliver to them twice.+ ticket_from = (ticket.email_from or "").lower()+ cc_list = [addr for addr in cc_list if addr != ticket_from]qs = Ticket.objects.filter(id=ticket.id, team=team)if not is_team_member and cc_list:qs.update(diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.pyindex 7e9283a6c57e..88cf31c17a69 100644--- a/products/conversations/backend/api/tests/test_email_endpoints.py+++ b/products/conversations/backend/api/tests/test_email_endpoints.py@@ -897,7 +897,9 @@ class TestSendEmailReplyMultiConfig(BaseTest):config1 = self._create_config("[email protected]", "aaa111")self._create_config("[email protected]", "bbb222")ticket = self._create_ticket(config1)- ticket.cc_participants = ["[email protected]", "[email protected]"]+ # Legacy tickets may carry the requester in cc_participants; they must not+ # be delivered to twice (they're already the To recipient).ticket.save(update_fields=["cc_participants"])_, outbox = self._run_reply(ticket)@@ -908,7 +910,7 @@ class TestSendEmailReplyMultiConfig(BaseTest):# Regression guard: must use the ticket's domain, not a shared/global one.assert args[0] == "example.com"- # Recipients include the customer and every CC participant.+ # Recipients include the customer and every CC participant, minus the requester.# MIME body carries the From header with the config's from_email.@@ -1540,14 +1542,33 @@ class TestEmailInboundCcParticipants(BaseTest):@parameterized.expand([- ("with_display_names", "Dev <[email protected]>, [email protected]", ["[email protected]", "[email protected]"]),- ("no_cc_header", None, []),+ # (_name, to_header, cc_header, expected)+ (+ "cc_with_display_names",+ None,+ "Dev <[email protected]>, [email protected]",+ ["[email protected]", "[email protected]"],+ ),+ ("no_recipients", None, None, []),+ # Direct recipient in To, support address only CC'd — the recipient must survive.+ (+ "to_recipient_kept_channel_dropped",+ "[email protected]",+ "[email protected]",+ ["[email protected]"],+ ),+ # Channel's own address and the sender are never participants.+ ("channel_and_sender_excluded", "[email protected], [email protected]", None, []),+ # To + Cc merge and dedupe.+ ("to_and_cc_merged", "[email protected]", "[email protected]", ["[email protected]", "[email protected]"]),])@patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)- def test_new_ticket_cc_participants(self, _name, cc_header, expected, _mock_sig):+ def test_new_ticket_participants(self, _name, to_header, cc_header, expected, _mock_sig):data = self._base_data(f"<cc-{_name}@test.com>")+ if to_header:+ data["To"] = to_headerif cc_header:data["Cc"] = cc_headerresponse = self.client.post("/api/conversations/v1/email/inbound", data)@@ -1572,6 +1593,18 @@ class TestEmailInboundCcParticipants(BaseTest):ticket.refresh_from_db()assert ticket.cc_participants == ["[email protected]", "[email protected]"]+ # A participant reply-alls: the requester lands in To but is already the+ # reply target, so they must not be merged into cc_participants.+ data3 = self._base_data("<[email protected]>")+ data3["from"] = "[email protected]"+ data3["In-Reply-To"] = "<[email protected]>"+ data3["To"] = "[email protected], [email protected]"+ data3["Cc"] = "[email protected]"+ self.client.post("/api/conversations/v1/email/inbound", data3)++ ticket.refresh_from_db()+ assert ticket.cc_participants == ["[email protected]", "[email protected]"]+class TestEmailInboundAttachments(BaseTest):def setUp(self):diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex affa6a6b5b74..6919e367c991 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -743,17 +743,21 @@ def _process_outbox_row(outbox: EmailOutboxMessage) -> None:from_email = formataddr((config.from_name or author_name, config.from_email))+ # Tickets created before To/Cc participant filtering may still have the requester+ # persisted in cc_participants; drop them here so they aren't delivered to twice.+ cc = [addr for addr in (ticket.cc_participants or []) if addr.lower() != ticket.email_from.lower()]+email_message = mail.EmailMultiAlternatives(subject=subject,body=txt_body,from_email=from_email,to=[ticket.email_from],- cc=ticket.cc_participants or [],+ cc=cc,headers=headers,)email_message.attach_alternative(html_body, "text/html")- recipients = [ticket.email_from, *(ticket.cc_participants or [])]+ recipients = [ticket.email_from, *cc]mime_bytes = email_message.message().as_bytes(linesep="\r\n")try: