: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
feat: email outbox (#60858)
Alex Vaaaf74d3a283
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.pyindex b7306cf07e7e..bc799724a6f1 100644--- a/.github/scripts/check-idor-model-coverage.py+++ b/.github/scripts/check-idor-model-coverage.py@@ -132,6 +132,9 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st"AsyncDeletion","AsyncMigration","AsyncMigrationError",+ # Outbound email delivery queue — looked up by PK / comment FK from internal+ # tasks (send + sweeper), never by user-supplied ID through an API.+ "EmailOutboxMessage","InsightCachingState","InstanceSetting","Schedule",diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex ceca99725e10..67d6a0fcc6f7 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -69,7 +69,7 @@ from posthog.tasks.team_llm_gateway_policy import refresh_expiring_llm_gateway_pfrom posthog.tasks.team_metadata import cleanup_stale_expiry_tracking_task, refresh_expiring_team_metadata_cache_entriesfrom posthog.utils import get_crontab, get_instance_region-from products.conversations.backend.tasks import wake_snoozed_tickets+from products.conversations.backend.tasks import flush_pending_email_replies, wake_snoozed_ticketsfrom products.data_modeling.backend.tasks.cleanup_test_saved_queries import cleanup_expired_test_saved_queriesfrom products.endpoints.backend.tasks import deactivate_stale_materializationsfrom products.feature_flags.backend.tasks import (@@ -624,3 +624,11 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:wake_snoozed_tickets.s(),name="wake snoozed conversation tickets",)++ # Re-drive queued outbound support email replies (survives a multi-day email provider outage)+ add_periodic_task_with_expiry(+ sender,+ crontab(minute="*"),+ flush_pending_email_replies.s(),+ name="flush pending conversation email replies",+ )diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.pyindex c687b4f6e3d0..6460adc652ec 100644--- a/products/conversations/backend/api/tests/test_email_endpoints.py+++ b/products/conversations/backend/api/tests/test_email_endpoints.py@@ -1,3 +1,4 @@+from datetime import timedeltafrom io import BytesIOfrom posthog.test.base import BaseTest@@ -5,6 +6,7 @@ from unittest.mock import MagicMock, patchfrom django.core.files.uploadedfile import SimpleUploadedFilefrom django.test import Client+from django.utils import timezonefrom parameterized import parameterizedfrom PIL import Image@@ -13,8 +15,14 @@ from posthog.models.comment import Commentfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Team-from products.conversations.backend.mailgun import MailgunDomainConflict-from products.conversations.backend.models import EmailChannel+from products.conversations.backend.mailgun import (+ MailgunDomainConflict,+ MailgunDomainNotRegistered,+ MailgunNotConfigured,+ MailgunPermanentError,+ MailgunTransientError,+)+from products.conversations.backend.models import EmailChannel, EmailOutboxMessagefrom products.conversations.backend.models.ticket import Ticket@@ -666,36 +674,48 @@ class TestSendEmailReplyMultiConfig(BaseTest):email_from="[email protected]",)- def _run_reply(self, ticket: Ticket, content: str = "Reply from agent") -> Comment:- from products.conversations.backend.tasks import send_email_reply-+ def _create_outbox(+ self, ticket: Ticket, content: str = "Reply from agent", rich_content: dict | None = None+ ) -> tuple[Comment, EmailOutboxMessage]:+ """Create the reply comment + its durable outbox row, mirroring the signal path."""comment = Comment.objects.create(team=self.team,scope="conversations_ticket",item_id=str(ticket.id),content=content,+ rich_content=rich_content,+ created_by=self.user,+ item_context={"author_type": "support"},)+ # The post_save signal creates the outbox row when created_by is set; fall back+ # to creating it explicitly so the test is robust to signal gating changes.+ outbox = EmailOutboxMessage.objects.filter(comment=comment).first()+ if outbox is None:+ outbox = EmailOutboxMessage.objects.create(+ team=self.team,+ ticket=ticket,+ comment=comment,+ message_id="<[email protected]>",+ )+ return comment, outbox- send_email_reply(- ticket_id=str(ticket.id),- team_id=self.team.id,- comment_id=str(comment.id),- content=content,- rich_content=None,- author_name="Agent",- )- return comment+ def _run_reply(self, ticket: Ticket, content: str = "Reply from agent") -> tuple[Comment, EmailOutboxMessage]:+ from products.conversations.backend.tasks import send_email_reply++ comment, outbox = self._create_outbox(ticket, content=content)+ send_email_reply(str(outbox.id))+ outbox.refresh_from_db()+ return comment, outbox@patch("products.conversations.backend.tasks.send_mime")- @patch("products.conversations.backend.tasks.get_instance_setting", return_value="mg.posthog.com")- def test_send_email_reply_uses_ticket_config(self, _mock_setting: MagicMock, mock_send_mime: MagicMock):+ def test_send_email_reply_uses_ticket_config(self, mock_send_mime: MagicMock):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]"]ticket.save(update_fields=["cc_participants"])- self._run_reply(ticket)+ _, outbox = self._run_reply(ticket)mock_send_mime.assert_called_once()args, kwargs = mock_send_mime.call_args@@ -716,85 +736,154 @@ class TestSendEmailReplyMultiConfig(BaseTest):# RFC 5322 wants CRLF; Django's default is LF-only.assert b"\r\n" in mime_bytes- @patch("products.conversations.backend.tasks.send_mime")- @patch("products.conversations.backend.tasks.get_instance_setting", return_value="mg.posthog.com")- def test_send_email_reply_permanent_error_does_not_retry(self, _mock_setting: MagicMock, mock_send_mime: MagicMock):- from products.conversations.backend.mailgun import MailgunPermanentError+ assert outbox.status == EmailOutboxMessage.Status.SENT+ assert outbox.sent_at is not None+ @parameterized.expand(+ [+ # name, error raised by send_mime, whether it flips the domain back to unverified+ ("permanent_error", MailgunPermanentError("bad recipient"), False),+ ("not_configured", MailgunNotConfigured("mailgun not configured"), False),+ ("domain_not_registered", MailgunDomainNotRegistered("gone from mailgun"), True),+ ]+ )+ @patch("products.conversations.backend.tasks.send_mime")+ def test_send_email_reply_terminal_errors_mark_failed(+ self, _name: str, error: Exception, flips_domain_verified: bool, mock_send_mime: MagicMock+ ):config = self._create_config("[email protected]", "aaa111")ticket = self._create_ticket(config)- mock_send_mime.side_effect = MailgunPermanentError("bad recipient")+ mock_send_mime.side_effect = error- self._run_reply(ticket)+ _, outbox = self._run_reply(ticket)- # One attempt, no Celery retry.+ # One attempt, no retry, terminal failure recorded.assert mock_send_mime.call_count == 1+ assert outbox.status == EmailOutboxMessage.Status.FAILED_PERMANENT- @patch("products.conversations.backend.tasks.send_mime")- @patch("products.conversations.backend.tasks.get_instance_setting", return_value="mg.posthog.com")- def test_send_email_reply_domain_not_registered_flips_verified(- self, _mock_setting: MagicMock, mock_send_mime: MagicMock- ):- from products.conversations.backend.mailgun import MailgunDomainNotRegistered+ config.refresh_from_db()+ assert config.domain_verified is (not flips_domain_verified)+ @patch("products.conversations.backend.tasks.send_mime")+ def test_send_email_reply_transient_error_schedules_retry(self, mock_send_mime: MagicMock):+ """Transient errors must NOT be dropped or raised — the row stays pending with a+ backed-off next_attempt_at so the sweeper re-drives it. This is what survives a+ multi-day provider outage."""config = self._create_config("[email protected]", "aaa111")ticket = self._create_ticket(config)- mock_send_mime.side_effect = MailgunDomainNotRegistered("gone from mailgun")+ mock_send_mime.side_effect = MailgunTransientError("mailgun 503")- self._run_reply(ticket)+ before = timezone.now()+ _, outbox = self._run_reply(ticket, content="Reply")- config.refresh_from_db()- assert config.domain_verified is False+ assert mock_send_mime.call_count == 1+ assert outbox.status == EmailOutboxMessage.Status.PENDING+ assert outbox.attempts == 1+ assert outbox.next_attempt_at > before+ assert outbox.locked_until is None@patch("products.conversations.backend.tasks.send_mime")- @patch("products.conversations.backend.tasks.get_instance_setting", return_value="mg.posthog.com")- def test_send_email_reply_transient_error_is_not_swallowed(- self, _mock_setting: MagicMock, mock_send_mime: MagicMock- ):- """Contrast with the permanent-error path: transient errors must NOT be- silently swallowed — they need to propagate so Celery can retry them.- In eager test mode the exception bubbles up directly; in production the- @shared_task wrapper converts it into a Celery Retry signal."""- from products.conversations.backend.mailgun import MailgunTransientError-+ def test_send_email_reply_reuses_message_id_across_attempts(self, mock_send_mime: MagicMock):+ """A retried send must reuse the same Message-ID so threading/dedup stay stable."""config = self._create_config("[email protected]", "aaa111")ticket = self._create_ticket(config)+ # First attempt fails transiently.mock_send_mime.side_effect = MailgunTransientError("mailgun 503")+ _, outbox = self._run_reply(ticket, content="Reply")+ original_message_id = outbox.message_id++ # Make it due again and let the next attempt succeed.+ from products.conversations.backend.tasks import send_email_reply++ EmailOutboxMessage.objects.filter(id=outbox.id).update(next_attempt_at=timezone.now(), locked_until=None)+ mock_send_mime.side_effect = None+ send_email_reply(str(outbox.id))- # In eager mode, .retry(exc=e) re-raises e directly without re-executing- # the task, so call_count stays at 1 — we can't assert the retry loop ran.- # What we CAN assert: the exception type propagates (vs permanent errors,- # which are swallowed). That's the behavioral contract the production- # worker depends on to trigger its real retry loop.- with self.assertRaises(MailgunTransientError):- self._run_reply(ticket, content="Reply")+ outbox.refresh_from_db()+ assert outbox.status == EmailOutboxMessage.Status.SENT+ assert outbox.message_id == original_message_id+ # Both attempts carried the same Message-ID header.+ first_mime = mock_send_mime.call_args_list[0].args[1]+ second_mime = mock_send_mime.call_args_list[1].args[1]+ assert original_message_id.encode() in first_mime+ assert original_message_id.encode() in second_mime- def test_send_email_reply_skips_when_no_config(self):+ @patch("products.conversations.backend.tasks.send_mime")+ def test_send_email_reply_idempotent_when_already_sent(self, mock_send_mime: MagicMock):from products.conversations.backend.tasks import send_email_reply+ config = self._create_config("[email protected]", "aaa111")+ ticket = self._create_ticket(config)+ _, outbox = self._create_outbox(ticket)+ EmailOutboxMessage.objects.filter(id=outbox.id).update(status=EmailOutboxMessage.Status.SENT)++ send_email_reply(str(outbox.id))++ mock_send_mime.assert_not_called()++ @patch("products.conversations.backend.tasks.send_mime")+ def test_send_email_reply_marks_failed_when_no_config(self, mock_send_mime: MagicMock):ticket = self._create_ticket(None)- from posthog.models.comment import Comment+ _, outbox = self._run_reply(ticket, content="Reply")++ assert outbox.status == EmailOutboxMessage.Status.FAILED_PERMANENT+ mock_send_mime.assert_not_called()++ def test_outbox_row_created_in_signal_survives_without_broker(self):+ """The durable outbox row is created in the comment's transaction, so a reply is+ recoverable even if the broker never picks up the immediate send task."""+ config = self._create_config("[email protected]", "aaa111")+ ticket = self._create_ticket(config)comment = Comment.objects.create(team=self.team,scope="conversations_ticket",item_id=str(ticket.id),content="Reply",+ created_by=self.user,+ item_context={"author_type": "support"},)- # Should return without error (logs warning, doesn't crash)- send_email_reply(- ticket_id=str(ticket.id),- team_id=self.team.id,- comment_id=str(comment.id),- content="Reply",- rich_content=None,- author_name="Agent",- )+ outbox = EmailOutboxMessage.objects.filter(comment=comment).first()+ assert outbox is not None+ assert outbox.status == EmailOutboxMessage.Status.PENDING+ assert outbox.message_id++ @parameterized.expand(+ [+ # name, scenario, expect send_mime called, resulting status+ ("due_row_is_sent", "due", True, EmailOutboxMessage.Status.SENT),+ ("locked_row_is_skipped", "locked", False, EmailOutboxMessage.Status.PENDING),+ ("expired_row_is_given_up", "expired", False, EmailOutboxMessage.Status.FAILED_PERMANENT),+ ]+ )+ @patch("products.conversations.backend.tasks.send_mime")+ def test_flush_pending_email_replies(+ self, _name: str, scenario: str, expect_send: bool, expected_status: str, mock_send_mime: MagicMock+ ):+ from products.conversations.backend.tasks import EMAIL_OUTBOX_MAX_AGE, flush_pending_email_replies++ config = self._create_config("[email protected]", "aaa111")+ ticket = self._create_ticket(config)+ _, outbox = self._create_outbox(ticket)++ now = timezone.now()+ if scenario == "locked":+ EmailOutboxMessage.objects.filter(id=outbox.id).update(locked_until=now + timedelta(minutes=5))+ elif scenario == "expired":+ EmailOutboxMessage.objects.filter(id=outbox.id).update(+ created_at=now - EMAIL_OUTBOX_MAX_AGE - timedelta(hours=1), next_attempt_at=now+ )++ flush_pending_email_replies()++ outbox.refresh_from_db()+ assert mock_send_mime.called is expect_send+ assert outbox.status == expected_statusclass TestEmailInboundDmarcRewrite(BaseTest):diff --git a/products/conversations/backend/migrations/0037_emailoutboxmessage.py b/products/conversations/backend/migrations/0037_emailoutboxmessage.pynew file mode 100644index 000000000000..e0aaf0a8d312--- /dev/null+++ b/products/conversations/backend/migrations/0037_emailoutboxmessage.py@@ -0,0 +1,81 @@+# Generated by Django 5.2.14 on 2026-06-01 10:20++import django.utils.timezone+import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0036_github_issues_channel"),+ ("posthog", "1190_team_llm_gateway_metadata"),+ ]++ operations = [+ migrations.CreateModel(+ name="EmailOutboxMessage",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.uuid7,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ ("message_id", models.CharField(max_length=255)),+ (+ "status",+ models.CharField(+ choices=[+ ("pending", "Pending"),+ ("sent", "Sent"),+ ("failed_permanent", "Failed (permanent)"),+ ],+ default="pending",+ max_length=20,+ ),+ ),+ ("attempts", models.PositiveIntegerField(default=0)),+ ("last_error", models.TextField(blank=True, default="")),+ (+ "next_attempt_at",+ models.DateTimeField(default=django.utils.timezone.now),+ ),+ ("locked_until", models.DateTimeField(blank=True, null=True)),+ ("created_at", models.DateTimeField(auto_now_add=True)),+ ("updated_at", models.DateTimeField(auto_now=True)),+ ("sent_at", models.DateTimeField(blank=True, null=True)),+ (+ "comment",+ models.OneToOneField(+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.comment",+ ),+ ),+ (+ "team",+ models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="posthog.team"),+ ),+ (+ "ticket",+ models.ForeignKey(+ on_delete=django.db.models.deletion.CASCADE,+ to="conversations.ticket",+ ),+ ),+ ],+ options={+ "db_table": "posthog_conversations_email_outbox_message",+ "indexes": [+ models.Index(+ fields=["status", "next_attempt_at"],+ name="posthog_con_outbox_due_idx",+ )+ ],+ },+ ),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex f3441497f83a..972dba1501fe 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0036_github_issues_channel+0037_emailoutboxmessagediff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.pyindex e3e3c99194e7..8bf5316afee8 100644--- a/products/conversations/backend/models/__init__.py+++ b/products/conversations/backend/models/__init__.py@@ -1,6 +1,7 @@from .assignment import TicketAssignmentfrom .constants import Channel, ChannelDetail, Priority, RuleType, Statusfrom .email_message_mapping import EmailMessageMapping+from .email_outbox_message import EmailOutboxMessagefrom .github_comment_mapping import GithubCommentMappingfrom .restore_token import ConversationRestoreTokenfrom .team_conversations_email_config import EmailChannel@@ -15,6 +16,7 @@ __all__ = ["ConversationRestoreToken","EmailChannel","EmailMessageMapping",+ "EmailOutboxMessage","GithubCommentMapping","Priority","RuleType",diff --git a/products/conversations/backend/models/email_outbox_message.py b/products/conversations/backend/models/email_outbox_message.pynew file mode 100644index 000000000000..72079713eb2b--- /dev/null+++ b/products/conversations/backend/models/email_outbox_message.py@@ -0,0 +1,55 @@+from django.db import models+from django.utils import timezone++from posthog.models.utils import UUIDModel++from .ticket import Ticket+++class EmailOutboxMessage(UUIDModel):+ """Durable outbox for outbound email replies.++ The source of truth for whether an agent's reply has been delivered. A row is+ created in the same transaction as the reply comment, so it survives a broker+ outage; a periodic sweeper re-drives non-terminal rows until they send or hit+ the age cutoff. This is what lets outbound replies survive a multi-day Mailgun+ block instead of being dropped after a handful of broker-parked retries.+ """++ class Status(models.TextChoices):+ PENDING = "pending", "Pending"+ SENT = "sent", "Sent"+ FAILED_PERMANENT = "failed_permanent", "Failed (permanent)"++ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE)+ ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE)+ # One outbox row per agent reply comment — the idempotency key across retries.+ comment = models.OneToOneField("posthog.Comment", on_delete=models.CASCADE)++ # Stable Message-ID for the outbound email, generated once and reused on every+ # attempt so threading headers and dedup stay consistent across resends.+ message_id = models.CharField(max_length=255)++ status = models.CharField(max_length=20, choices=Status.choices, default=Status.PENDING)+ attempts = models.PositiveIntegerField(default=0)+ last_error = models.TextField(blank=True, default="")++ # Scheduler key — the sweeper picks up pending rows whose next_attempt_at has passed.+ next_attempt_at = models.DateTimeField(default=timezone.now)+ # Lightweight lease so the immediate task and the sweeper don't double-send.+ locked_until = models.DateTimeField(null=True, blank=True)++ created_at = models.DateTimeField(auto_now_add=True)+ updated_at = models.DateTimeField(auto_now=True)+ sent_at = models.DateTimeField(null=True, blank=True)++ class Meta:+ app_label = "conversations"+ db_table = "posthog_conversations_email_outbox_message"+ indexes = [+ # Sweeper query: pending rows due for an attempt, oldest first.+ models.Index(fields=["status", "next_attempt_at"], name="posthog_con_outbox_due_idx"),+ ]++ def __str__(self) -> str:+ return f"EmailOutboxMessage({self.message_id} -> ticket={self.ticket_id}, status={self.status})"diff --git a/products/conversations/backend/signals.py b/products/conversations/backend/signals.pyindex 75aa3c54c3b5..1969b76f91c3 100644--- a/products/conversations/backend/signals.py+++ b/products/conversations/backend/signals.py@@ -1,3 +1,4 @@+from email.utils import make_msgidfrom typing import Any, castfrom django.db import transaction@@ -12,11 +13,12 @@ from posthog.event_usage import report_team_action, report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Userfrom posthog.models.comment import Comment+from posthog.models.instance_setting import get_instance_settingfrom posthog.tasks.email import send_new_ticket_notificationfrom .cache import invalidate_messages_cache, invalidate_tickets_cachefrom .events import capture_message_received, capture_message_sent, capture_ticket_created-from .models import Ticket+from .models import EmailOutboxMessage, Ticketfrom .models.constants import Channelfrom .tasks import post_reply_to_github, post_reply_to_slack, post_reply_to_teams, send_email_reply@@ -352,43 +354,47 @@ def send_email_reply_on_team_message(sender, instance: Comment, created: bool, *team_id = instance.team_iditem_id = instance.item_id- comment_id = str(instance.id)- content = instance.content or ""- rich_content = instance.rich_content- created_by = instance.created_by+ comment = instance++ # Resolve the ticket + email config now (synchronously, in the comment's transaction)+ # so the durable outbox row commits atomically with the reply. If Celery/the broker+ # is down, the row still exists and flush_pending_email_replies will send it.+ ticket = (+ Ticket.objects.select_related("team", "email_config")+ .filter(id=item_id, team_id=team_id, channel_source=Channel.EMAIL)+ .first()+ )+ if not ticket or not ticket.email_from:+ return- def do_send_email():- try:- ticket = Ticket.objects.filter(- id=item_id,- team_id=team_id,- channel_source=Channel.EMAIL,- ).first()+ settings_dict = ticket.team.conversations_settings or {}+ if not settings_dict.get("email_enabled"):+ return- if not ticket or not ticket.email_from:- return+ config = ticket.email_config+ inbound_domain = get_instance_setting("CONVERSATIONS_EMAIL_INBOUND_DOMAIN") or (config.domain if config else None)+ message_id = make_msgid(domain=inbound_domain) if inbound_domain else make_msgid()- team = ticket.team- settings_dict = team.conversations_settings or {}- if not settings_dict.get("email_enabled"):- return+ # One outbox row per reply comment; get_or_create keeps the signal idempotent.+ outbox, _ = EmailOutboxMessage.objects.get_or_create(+ comment=comment,+ defaults={+ "team_id": team_id,+ "ticket": ticket,+ "message_id": message_id,+ },+ )- author_name = ""- if created_by:- author_name = f"{created_by.first_name} {created_by.last_name}".strip() or created_by.email+ outbox_id = str(outbox.id)- cast(Any, send_email_reply).delay(- ticket_id=str(ticket.id),- team_id=team_id,- comment_id=comment_id,- content=content,- rich_content=rich_content,- author_name=author_name,- )+ def enqueue_immediate_send():+ # Low-latency happy path; the periodic sweeper is the durability backstop.+ try:+ cast(Any, send_email_reply).delay(outbox_id=outbox_id)except Exception:logger.exception("email_reply_signal_failed", item_id=item_id)- transaction.on_commit(do_send_email)+ transaction.on_commit(enqueue_immediate_send)@receiver(post_save, sender=Comment)diff --git a/products/conversations/backend/tasks.py b/products/conversations/backend/tasks.pyindex 676880de015b..89198f8d4b90 100644--- a/products/conversations/backend/tasks.py+++ b/products/conversations/backend/tasks.py@@ -1,7 +1,8 @@"""Celery tasks for the conversations product."""import html as html_mod-from email.utils import formataddr, make_msgid+from datetime import timedelta+from email.utils import formataddrfrom typing import Any, castfrom urllib.parse import quote, urlparsefrom uuid import UUID@@ -9,6 +10,8 @@ from uuid import UUIDfrom django.core import mailfrom django.core.cache import cachefrom django.db import IntegrityError, models, transaction+from django.db.models.fields.json import JSONField+from django.db.models.functions import Coalescefrom django.utils import timezoneimport requests@@ -16,7 +19,6 @@ import structlogfrom celery import shared_taskfrom posthog.models.comment import Comment as CommentModel-from posthog.models.instance_setting import get_instance_settingfrom posthog.models.team import Teamfrom posthog.models.uploaded_media import UploadedMediafrom posthog.scoping_audit import skip_team_scope_audit@@ -38,6 +40,7 @@ from products.conversations.backend.mailgun import ()from products.conversations.backend.models import (EmailMessageMapping,+ EmailOutboxMessage,GithubCommentMapping,TeamConversationsSlackConfig,TeamConversationsTeamsConfig,@@ -422,68 +425,120 @@ def _read_image_bytes_for_slack_upload(team_id: int, image_url: str) -> bytes |return payload-@shared_task(ignore_result=True, max_retries=3, default_retry_delay=10)-@skip_team_scope_audit-def send_email_reply(- ticket_id: str,- team_id: int,- comment_id: str,- content: str,- rich_content: dict | None,- author_name: str,-) -> None:- """Send a team member's reply to the customer via SMTP email."""- try:- team = Team.objects.get(id=team_id)- except Team.DoesNotExist:- logger.warning("email_reply_team_not_found", team_id=team_id)- return+# Outbound email outbox tuning. Durability lives in the Postgres outbox row, not+# the broker: a periodic sweeper re-drives pending rows until they send or hit the+# age cutoff, so an agent reply survives a multi-day Mailgun block.+EMAIL_OUTBOX_SEND_LOCK_SECONDS = 120 # app-level lease covering a single send attempt+EMAIL_OUTBOX_BACKOFF_BASE_SECONDS = 60+EMAIL_OUTBOX_BACKOFF_MAX_SECONDS = 3600 # cap retry spacing at ~1h during a long outage+EMAIL_OUTBOX_MAX_AGE = timedelta(days=5) # give up past this (comfortably > a Fri-Mon block)+EMAIL_OUTBOX_FLUSH_BATCH_SIZE = 100+++def _set_comment_delivery_status(team_id: int, comment_id: UUID, status_value: str) -> None:+ """Denormalize delivery status onto the comment's item_context so the agent UI can+ show a sending/failed badge. Uses a queryset update to avoid re-firing Comment signals.++ Merges at the DB level (JSONB ``||``) rather than read-modify-write: a concurrent+ edit to another key (e.g. an agent flipping ``is_private``) must not be clobbered.+ The dict values flow through ORM ``Value`` params, so this is fully parameterized.+ """+ merged = models.Func(+ Coalesce("item_context", models.Value({}, output_field=JSONField())),+ models.Value({"email_delivery_status": status_value}, output_field=JSONField()),+ template="%(expressions)s",+ arg_joiner=" || ",+ output_field=JSONField(),+ )+ CommentModel.objects.filter(id=comment_id, team_id=team_id).update(item_context=merged)++def _mark_outbox_sent(outbox: EmailOutboxMessage) -> None:+ outbox.status = EmailOutboxMessage.Status.SENT+ outbox.sent_at = timezone.now()+ outbox.locked_until = None+ outbox.last_error = ""+ outbox.save(update_fields=["status", "sent_at", "locked_until", "last_error", "updated_at"])+ # Record the outbound message mapping for threading (best-effort).try:- ticket = Ticket.objects.select_related("email_config").get(id=ticket_id, team=team)- except Ticket.DoesNotExist:- logger.warning("email_reply_ticket_not_found", ticket_id=ticket_id)- return+ EmailMessageMapping.objects.get_or_create(+ message_id=outbox.message_id,+ team_id=outbox.team_id,+ defaults={"ticket_id": outbox.ticket_id, "comment_id": outbox.comment_id},+ )+ except Exception:+ logger.exception("email_reply_mapping_failed", outbox_id=str(outbox.id), message_id=outbox.message_id)+ _set_comment_delivery_status(outbox.team_id, outbox.comment_id, "sent")+++def _mark_outbox_failed(outbox: EmailOutboxMessage, error: str) -> None:+ outbox.status = EmailOutboxMessage.Status.FAILED_PERMANENT+ outbox.last_error = error[:2000]+ outbox.locked_until = None+ outbox.save(update_fields=["status", "last_error", "locked_until", "updated_at"])+ _set_comment_delivery_status(outbox.team_id, outbox.comment_id, "failed")+++def _schedule_outbox_retry(outbox: EmailOutboxMessage, error: str) -> None:+ outbox.attempts += 1+ backoff = min(+ EMAIL_OUTBOX_BACKOFF_BASE_SECONDS * (2 ** min(outbox.attempts, 16)),+ EMAIL_OUTBOX_BACKOFF_MAX_SECONDS,+ )+ outbox.next_attempt_at = timezone.now() + timedelta(seconds=backoff)+ outbox.last_error = error[:2000]+ outbox.locked_until = None+ outbox.save(update_fields=["attempts", "next_attempt_at", "last_error", "locked_until", "updated_at"])+ _set_comment_delivery_status(outbox.team_id, outbox.comment_id, "sending")+++def _process_outbox_row(outbox: EmailOutboxMessage) -> None:+ """Render and send one already-claimed outbox row, recording the outcome.+ The caller must have taken the lease (locked_until) before calling this. Uses the+ row's stored message_id so every attempt is byte-stable for threading and dedup.+ """+ ticket = outbox.ticketconfig = ticket.email_config+ comment = outbox.comment+if not config:- logger.warning("email_reply_no_config", team_id=team_id, ticket_id=ticket_id)+ _mark_outbox_failed(outbox, "no email config")return-if not config.domain_verified:- logger.warning("email_reply_domain_not_verified", team_id=team_id, domain=config.domain)+ _mark_outbox_failed(outbox, f"domain {config.domain} not verified")return-if not ticket.email_from:- logger.warning("email_reply_no_customer_email", ticket_id=ticket_id)+ _mark_outbox_failed(outbox, "no customer email")return+ author_name = ""+ if comment.created_by:+ author_name = (+ f"{comment.created_by.first_name} {comment.created_by.last_name}".strip() or comment.created_by.email+ )+# Build threading headers from the latest inbound message on this ticket- latest_mapping = EmailMessageMapping.objects.filter(ticket=ticket, team=team).order_by("-created_at").first()- headers: dict[str, str] = {}+ latest_mapping = (+ EmailMessageMapping.objects.filter(ticket_id=ticket.id, team_id=outbox.team_id).order_by("-created_at").first()+ )+ headers: dict[str, str] = {"Message-ID": outbox.message_id}if latest_mapping:headers["In-Reply-To"] = latest_mapping.message_id- # Collect all message IDs for References headerall_ids = list(- EmailMessageMapping.objects.filter(ticket=ticket, team=team)+ EmailMessageMapping.objects.filter(ticket_id=ticket.id, team_id=outbox.team_id).order_by("created_at").values_list("message_id", flat=True))if all_ids:headers["References"] = " ".join(all_ids)- # Generate a new Message-ID for the outbound email- inbound_domain = get_instance_setting("CONVERSATIONS_EMAIL_INBOUND_DOMAIN") or config.domain- outbound_message_id = make_msgid(domain=inbound_domain)- headers["Message-ID"] = outbound_message_id-- # Build email body- if rich_content:- html_body = rich_content_to_html(rich_content)- txt_body = rich_content_to_markdown(rich_content, include_images=False)+ if comment.rich_content:+ html_body = rich_content_to_html(comment.rich_content)+ txt_body = rich_content_to_markdown(comment.rich_content, include_images=False)else:- txt_body = content- html_body = f"<p>{html_mod.escape(content)}</p>"+ txt_body = comment.content or ""+ html_body = f"<p>{html_mod.escape(comment.content or '')}</p>"subject = ticket.email_subject or "Your support request"is_reply = latest_mapping is not None@@ -508,47 +563,107 @@ def send_email_reply(try:send_mime(config.domain, mime_bytes, recipients=recipients)except MailgunTransientError as e:- logger.warning("email_reply_send_transient_failure", ticket_id=ticket_id, error=str(e))- raise cast(Any, send_email_reply).retry(exc=e)+ # Retriable — keep the row pending and back off; the sweeper re-drives it.+ logger.warning("email_reply_send_transient_failure", outbox_id=str(outbox.id), error=str(e))+ _schedule_outbox_retry(outbox, str(e))+ returnexcept MailgunDomainNotRegistered:- logger.exception(- "email_reply_send_domain_not_registered",- ticket_id=ticket_id,- team_id=team_id,- domain=config.domain,- )+ logger.exception("email_reply_send_domain_not_registered", outbox_id=str(outbox.id), domain=config.domain)config.mark_domain_unverified()+ _mark_outbox_failed(outbox, "domain not registered with Mailgun")return- except (MailgunPermanentError, MailgunNotConfigured):- logger.exception(- "email_reply_send_permanent_failure",- ticket_id=ticket_id,- team_id=team_id,- domain=config.domain,- )+ except (MailgunPermanentError, MailgunNotConfigured) as e:+ logger.exception("email_reply_send_permanent_failure", outbox_id=str(outbox.id), domain=config.domain)+ _mark_outbox_failed(outbox, str(e))return- # Record the outbound message mapping for threading (best-effort, don't retry on failure)- try:- comment_obj = CommentModel.objects.get(id=comment_id, team=team)- EmailMessageMapping.objects.create(- message_id=outbound_message_id,- team=team,- ticket=ticket,- comment=comment_obj,- )- except Exception:- logger.exception("email_reply_mapping_failed", ticket_id=ticket_id, message_id=outbound_message_id)-+ _mark_outbox_sent(outbox)logger.info("email_reply_sent",- ticket_id=ticket_id,- team_id=team_id,+ outbox_id=str(outbox.id),+ team_id=outbox.team_id,to=ticket.email_from,- message_id=outbound_message_id,+ message_id=outbox.message_id,)+def _claim_outbox_row(outbox_id: str) -> EmailOutboxMessage | None:+ """Take the app-level lease on a single pending, due, unlocked row. Returns the+ locked row, or None if it's gone, terminal, or already being worked by someone else.+ """+ now = timezone.now()+ with transaction.atomic():+ # of=("self",) locks only the outbox row — the select_related joins reach a+ # nullable email_config FK, and Postgres can't FOR UPDATE an outer-join side.+ outbox = (+ EmailOutboxMessage.objects.select_for_update(skip_locked=True, of=("self",))+ .select_related("ticket", "ticket__email_config", "comment", "comment__created_by")+ .filter(id=outbox_id, status=EmailOutboxMessage.Status.PENDING)+ .filter(models.Q(locked_until__isnull=True) | models.Q(locked_until__lte=now))+ .first()+ )+ if outbox is None:+ return None+ outbox.locked_until = now + timedelta(seconds=EMAIL_OUTBOX_SEND_LOCK_SECONDS)+ outbox.save(update_fields=["locked_until", "updated_at"])+ return outbox+++@shared_task(ignore_result=True)+@skip_team_scope_audit+def send_email_reply(outbox_id: str) -> None:+ """Attempt one delivery of a queued outbound email reply.++ Idempotent per outbox row: a no-op if the row is already sent/failed or currently+ leased. Durability does not depend on this task running — if the broker drops it,+ ``flush_pending_email_replies`` re-drives the row from Postgres.+ """+ outbox = _claim_outbox_row(outbox_id)+ if outbox is None:+ return+ _process_outbox_row(outbox)+++@shared_task(ignore_result=True)+@skip_team_scope_audit+def flush_pending_email_replies() -> None:+ """Re-drive pending outbound email replies on a schedule.++ This is what survives a multi-day Mailgun outage: the broker only ever holds+ short-lived tasks, while the durable state is the Postgres outbox row swept here.+ Rows older than EMAIL_OUTBOX_MAX_AGE are given up (visibly, as failed_permanent).++ Bounded to one batch per run; the every-minute schedule drains any larger backlog+ over successive runs, keeping a single invocation short.+ """+ now = timezone.now()+ cutoff = now - EMAIL_OUTBOX_MAX_AGE++ with transaction.atomic():+ batch = list(+ EmailOutboxMessage.objects.select_for_update(skip_locked=True, of=("self",))+ .select_related("ticket", "ticket__email_config", "comment", "comment__created_by")+ .filter(status=EmailOutboxMessage.Status.PENDING, next_attempt_at__lte=now)+ .filter(models.Q(locked_until__isnull=True) | models.Q(locked_until__lte=now))+ .order_by("next_attempt_at")[:EMAIL_OUTBOX_FLUSH_BATCH_SIZE]+ )+ for outbox in batch:+ outbox.locked_until = now + timedelta(seconds=EMAIL_OUTBOX_SEND_LOCK_SECONDS)+ outbox.save(update_fields=["locked_until", "updated_at"])++ if not batch:+ return++ for outbox in batch:+ if outbox.created_at < cutoff:+ logger.warning("email_reply_outbox_expired", outbox_id=str(outbox.id), attempts=outbox.attempts)+ _mark_outbox_failed(outbox, "exceeded max delivery age")+ continue+ _process_outbox_row(outbox)++ logger.info("flush_pending_email_replies_completed", count=len(batch))++@shared_task(bind=True, ignore_result=True, max_retries=2, default_retry_delay=5)def send_teams_help(self, activity: dict[str, Any], reply: bool = False) -> None:"""Post the help/welcome adaptive card (Teams Store cert 11.4.4.3).diff --git a/products/conversations/frontend/components/Chat/Message.tsx b/products/conversations/frontend/components/Chat/Message.tsxindex d985a9ac168a..48532327dea9 100644--- a/products/conversations/frontend/components/Chat/Message.tsx+++ b/products/conversations/frontend/components/Chat/Message.tsx@@ -1,6 +1,6 @@import { JSONContent } from '@tiptap/core'-import { IconCopy, IconLock } from '@posthog/icons'+import { IconCopy, IconLock, IconWarning } from '@posthog/icons'import { LemonButton, ProfilePicture, Tooltip } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'@@ -73,10 +73,21 @@ export function Message({ message, isCustomer, deliveryStatus }: MessageProps):)}</div><div className="flex items-center justify-end gap-1">- {deliveryStatus && (- <span className="text-xs text-muted-alt">- {deliveryStatus === 'read' ? 'Read' : 'Sent'}- </span>+ {message.emailDeliveryStatus === 'failed' ? (+ <Tooltip title="We couldn't deliver this email reply. Please check the email channel settings and contact support if the issue persists.">+ <span className="inline-flex items-center gap-0.5 text-xs text-danger">+ <IconWarning className="text-xs" />+ Failed to send+ </span>+ </Tooltip>+ ) : message.emailDeliveryStatus === 'sending' ? (+ <span className="text-xs text-muted-alt">Sending…</span>+ ) : (+ deliveryStatus && (+ <span className="text-xs text-muted-alt">+ {deliveryStatus === 'read' ? 'Read' : 'Sent'}+ </span>+ ))}</div></div>diff --git a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.tsindex 624ed0062805..8ffa0525ab63 100644--- a/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts+++ b/products/conversations/frontend/scenes/ticket/supportTicketSceneLogic.ts@@ -399,6 +399,7 @@ export const supportTicketSceneLogic = kea<supportTicketSceneLogicType>([createdBy: message.created_by,createdAt: message.created_at,isPrivate: message.item_context?.is_private || false,+ emailDeliveryStatus: message.item_context?.email_delivery_status,}}),],diff --git a/products/conversations/frontend/types.ts b/products/conversations/frontend/types.tsindex 38366af0f7bf..ed4ea00d236f 100644--- a/products/conversations/frontend/types.ts+++ b/products/conversations/frontend/types.ts@@ -137,6 +137,9 @@ export interface MessageAuthor {email?: string}+/** Delivery state of an outbound email reply, denormalized from the backend outbox. */+export type EmailDeliveryStatus = 'sending' | 'sent' | 'failed'+export interface ChatMessage {id: stringcontent: string@@ -146,6 +149,7 @@ export interface ChatMessage {createdBy?: MessageAuthor | nullcreatedAt: stringisPrivate?: boolean+ emailDeliveryStatus?: EmailDeliveryStatus}export const statusOptions: { value: TicketStatus | 'all'; label: string }[] = [