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(customer-analytics): add email sync settings (#81970)

Arthur Moreira de Deus5b00aa474573
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index ee90f4306435..6ad8e826ab4e 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -54,6 +54,7 @@ import {
WarehousePersonPropertiesSetting,
} from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/account/WarehousePersonPropertiesSetting'
import { CalendarSyncConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/calendar/CalendarSyncConfig'
+import { CustomerEmailConfig } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig'
import { CustomerAnalyticsDashboardEvents } from 'products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/events/CustomerAnalyticsDashboardEvents'
import { ExceptionAutocaptureToggle } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/exception_autocapture/ExceptionAutocaptureSettings'
import { SuppressionRules } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/suppression_rules/SuppressionRules'
@@ -462,6 +463,14 @@ export const SETTINGS_MAP: SettingSection[] = [
flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],
keywords: ['calendar', 'meetings', 'google', 'sync', 'accounts'],
},
+ {
+ id: 'customer-analytics-email-sync',
+ title: 'Email sync',
+ description: 'Connect your work email to show customer conversations on matching accounts.',
+ component: <CustomerEmailConfig />,
+ flag: ['CUSTOMER_ANALYTICS', 'CUSTOMER_ANALYTICS_CSP'],
+ keywords: ['email', 'inbox', 'forwarding', 'sync', 'accounts'],
+ },
{
id: 'customer-analytics-event-stream',
title: 'Event stream',
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index afa6330120b4..90378ab7b222 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -124,6 +124,7 @@ export type SettingId =
| 'customer-analytics-accounts'
| 'customer-analytics-calendar-sync'
| 'customer-analytics-dashboard-events'
+ | 'customer-analytics-email-sync'
| 'customer-analytics-event-stream'
| 'customer-analytics-group-properties'
| 'customer-analytics-person-properties'
diff --git a/products/conversations/README.md b/products/conversations/README.md
index 94f7063e30e9..b21418b1d8e1 100644
--- a/products/conversations/README.md
+++ b/products/conversations/README.md
@@ -1,5 +1,13 @@
# Conversations
+## Customer communication email
+
+Customer communication channels use a unique PostHog forwarding address. New channels remain pending until their owner completes Gmail forwarding confirmation.
+
+While setup is pending, the inbound webhook discards normal email. It stores only a short-lived Google confirmation action after Mailgun verifies the webhook, Google SPF and DKIM pass, the source mailbox matches the channel, and the action uses the expected Google host. The encrypted setup record is visible only through the owner-scoped setup flow and is deleted after use or expiration.
+
+After confirmation, incoming messages are stored as email threads. Customer analytics links those threads to matching accounts before exposing them in the account view.
+
## Management commands
### `run_support_reply`
diff --git a/products/conversations/backend/api/email_settings.py b/products/conversations/backend/api/email_settings.py
index 7905d960ba61..a309a9bc1f78 100644
--- a/products/conversations/backend/api/email_settings.py
+++ b/products/conversations/backend/api/email_settings.py
@@ -2,10 +2,12 @@
import uuid
import secrets
+from datetime import timedelta
from email.utils import formataddr, make_msgid
from django.core import mail
from django.db import IntegrityError, transaction
+from django.utils import timezone
import structlog
from drf_spectacular.utils import OpenApiResponse, extend_schema
@@ -32,15 +34,24 @@ from products.conversations.backend.mailgun import (
send_mime,
verify_domain as mailgun_verify_domain,
)
-from products.conversations.backend.models import EmailChannel, EmailChannelKind
+from products.conversations.backend.models import (
+ EmailChannel,
+ EmailChannelConnectionStatus,
+ EmailChannelKind,
+ EmailChannelSetup,
+ EmailChannelSetupProvider,
+)
from products.conversations.backend.models.team_conversations_email_config import (
MAX_CUSTOMER_COMMUNICATION_CHANNELS_PER_TEAM,
MAX_EMAIL_CONFIGS_PER_TEAM,
+ MAX_PENDING_CUSTOMER_COMMUNICATION_CHANNELS_PER_OWNER,
)
from products.conversations.backend.permissions import IsConversationsAdmin
logger = structlog.get_logger(__name__)
+CUSTOMER_EMAIL_SETUP_TTL = timedelta(hours=24)
+
def _get_team_from_request(request: Request) -> tuple[User, Team] | Response:
"""Extract authenticated user + team from request. Returns Response on failure."""
@@ -91,9 +102,13 @@ def _resolve_config_from_request(request: Request) -> tuple[User, Team, EmailCha
return user, team, config
-def _config_to_dict(config: EmailChannel, inbound_domain: str | None = None) -> dict:
- """Serialize a config to the API response shape."""
+def _config_to_dict(config: EmailChannel, inbound_domain: str | None = None) -> dict[str, object]:
forwarding_address = f"team-{config.inbound_token}@{inbound_domain}" if inbound_domain else None
+ setup: EmailChannelSetup | None
+ try:
+ setup = config.setup
+ except EmailChannelSetup.DoesNotExist:
+ setup = None
return {
"id": config.id,
"kind": config.kind,
@@ -105,21 +120,61 @@ def _config_to_dict(config: EmailChannel, inbound_domain: str | None = None) ->
"domain_verified": config.domain_verified,
"dns_records": config.dns_records,
"is_default": config.is_default,
+ "connection_status": config.connection_status,
+ "setup_expires_at": setup.expires_at if setup is not None else None,
+ "confirmation_available": bool(setup and setup.confirmation_action),
}
-def _release_domain_if_unused(team: Team, domain: str) -> None:
- """Best-effort removal of a Mailgun registration that no config ended up using.
+def _expire_customer_email_setups(*, team: Team, owner: User) -> None:
+ now = timezone.now()
+ expired_channel_ids = list(
+ EmailChannelSetup.objects.for_team(team.id)
+ .filter(channel__owner=owner, expires_at__lte=now)
+ .values_list("channel_id", flat=True)
+ )
+ if not expired_channel_ids:
+ return
+ with transaction.atomic():
+ EmailChannelSetup.objects.for_team(team.id).filter(
+ channel_id__in=expired_channel_ids,
+ expires_at__lte=now,
+ ).delete()
+ EmailChannel.objects.filter(
+ team=team,
+ owner=owner,
+ id__in=expired_channel_ids,
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ ).update(connection_status=EmailChannelConnectionStatus.CONFIRMATION_EXPIRED)
+
+
+def _release_expired_customer_email_reservation(*, from_email: str) -> None:
+ channel = (
+ EmailChannel.objects.select_for_update()
+ .filter(
+ from_email=from_email,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ )
+ .first()
+ )
+ if channel is None or channel.connection_status == EmailChannelConnectionStatus.ACTIVE:
+ return
+
+ setup = EmailChannelSetup.objects.for_team(channel.team_id).filter(channel=channel).first()
- Left in place, the registration would make every future connect for this
- domain fail with a domain conflict.
+ setup_expired = setup is None or setup.expires_at <= timezone.now()
+ if channel.connection_status == EmailChannelConnectionStatus.CONFIRMATION_EXPIRED or setup_expired:
+ channel.delete()
- The `exists()` check narrows but cannot fully close a TOCTOU window: a
- concurrent connect could persist a config on this domain between the check and
- the delete. Mailgun calls run outside the team-row lock by design, so we accept
- that window; the loser at worst re-registers on its next verify.
+
+def _release_domain_if_unused(team: Team, domain: str) -> None:
+ """Best-effort removal of a Mailgun registration that no support config uses.
+
+ Customer communication channels only receive captured mail, so they do not
+ own Mailgun sending-domain registrations. The support connect that loses a
+ concurrent race can re-register on its next verify.
"""
- if EmailChannel.objects.filter(domain=domain).exists():
+ if EmailChannel.objects.filter(domain=domain, kind=EmailChannelKind.SUPPORT).exists():
return
try:
mailgun_delete_domain(domain)
@@ -128,7 +183,7 @@ def _release_domain_if_unused(team: Team, domain: str) -> None:
def _try_reclaim_stranded_domain(team: Team, domain: str) -> dict | None:
- """Recover a domain stranded in our Mailgun account with no config referencing it.
+ """Recover a domain stranded in our Mailgun account with no support config referencing it.
A connect that registered the domain but failed to persist a config, or a
disconnect whose Mailgun delete failed, leaves such a registration behind —
@@ -141,7 +196,7 @@ def _try_reclaim_stranded_domain(team: Team, domain: str) -> dict | None:
Returns fresh DNS records when the domain was reclaimed, None when the
conflict stands.
"""
- if EmailChannel.objects.filter(domain=domain).exists():
+ if EmailChannel.objects.filter(domain=domain, kind=EmailChannelKind.SUPPORT).exists():
return None
# Decision phase (reads only). A lookup/verify failure here must leave the
@@ -169,7 +224,7 @@ def _try_reclaim_stranded_domain(team: Team, domain: str) -> dict | None:
# first check (Mailgun calls run outside the team-row lock by design). This narrows
# — does not close — that window, but the read-only decision phase above is where
# most of the latency sits, so the remaining window is small.
- if EmailChannel.objects.filter(domain=domain).exists():
+ if EmailChannel.objects.filter(domain=domain, kind=EmailChannelKind.SUPPORT).exists():
return None
# Mutation phase. If the delete lands but the re-add fails, the stale registration
@@ -278,6 +333,20 @@ class EmailChannelConfigSerializer(serializers.Serializer):
read_only=True,
help_text="Whether this support channel is the team's fallback sender.",
)
+ connection_status = serializers.ChoiceField(
+ choices=EmailChannelConnectionStatus.choices,
+ read_only=True,
+ help_text="Whether forwarding setup is pending, active, or expired.",
+ )
+ setup_expires_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="When the pending forwarding setup expires.",
+ )
+ confirmation_available = serializers.BooleanField(
+ read_only=True,
+ help_text="Whether an authenticated forwarding confirmation is ready for the owner.",
+ )
class EmailStatusResponseSerializer(serializers.Serializer):
@@ -297,6 +366,13 @@ class EmailChannelOperationResponseSerializer(serializers.Serializer):
ok = serializers.BooleanField(read_only=True, help_text="Whether the operation succeeded.")
+class EmailConfirmForwardingResponseSerializer(EmailChannelOperationResponseSerializer):
+ confirmation_url = serializers.URLField(
+ read_only=True,
+ help_text="Authenticated Google forwarding confirmation URL.",
+ )
+
+
class EmailSendTestResponseSerializer(EmailChannelOperationResponseSerializer):
sent_to = serializers.EmailField(read_only=True, help_text="Address that received the test email.")
@@ -307,6 +383,7 @@ class EmailStatusView(APIView):
permission_classes = [IsAuthenticated]
@extend_schema(
+ tags=["conversations"],
parameters=[EmailChannelKindQuerySerializer],
responses={
200: EmailStatusResponseSerializer,
@@ -323,22 +400,25 @@ class EmailStatusView(APIView):
query_serializer.is_valid(raise_exception=True)
kind = query_serializer.validated_data["kind"]
configs = EmailChannel.objects.filter(team=team, kind=kind)
- if kind == EmailChannelKind.CUSTOMER_COMMUNICATION and not _is_organization_admin(user, team):
+ if kind == EmailChannelKind.CUSTOMER_COMMUNICATION:
+ _expire_customer_email_setups(team=team, owner=user)
configs = configs.filter(owner=user)
- configs = configs.order_by("created_at")
+ configs = configs.select_related("setup").order_by("created_at")
inbound_domain = get_instance_setting("CONVERSATIONS_EMAIL_INBOUND_DOMAIN")
return Response({"configs": [_config_to_dict(c, inbound_domain) for c in configs]})
class EmailConnectView(APIView):
- permission_classes = [IsAuthenticated, IsConversationsAdmin]
+ permission_classes = [IsAuthenticated]
@extend_schema(
+ tags=["conversations"],
request=EmailConnectSerializer,
responses={
200: EmailConnectResponseSerializer,
400: OpenApiResponse(response=EmailChannelErrorSerializer),
+ 403: OpenApiResponse(response=EmailChannelErrorSerializer),
409: OpenApiResponse(response=EmailChannelErrorSerializer),
502: OpenApiResponse(response=EmailChannelErrorSerializer),
},
@@ -356,7 +436,11 @@ class EmailConnectView(APIView):
from_name: str = serializer.validated_data["from_name"]
kind: str = serializer.validated_data["kind"]
owner: User | None = None
- if kind == EmailChannelKind.CUSTOMER_COMMUNICATION:
+ is_admin = _is_organization_admin(user, team)
+ if kind == EmailChannelKind.SUPPORT:
+ if not is_admin:
+ return Response({"error": "Only organization admins can manage support email channels."}, status=403)
+ else:
membership = (
OrganizationMembership.objects.filter(
organization_id=team.organization_id,
@@ -369,6 +453,8 @@ class EmailConnectView(APIView):
if membership is None:
return Response({"error": "Owner must be an active member of this organization."}, status=400)
owner = membership.user
+ if owner.id != user.id and not is_admin:
+ return Response({"error": "You can only connect your own email address."}, status=403)
domain = from_email.split("@")[1]
inbound_domain = get_instance_setting("CONVERSATIONS_EMAIL_INBOUND_DOMAIN")
@@ -378,44 +464,53 @@ class EmailConnectView(APIView):
status=400,
)
- # Guard: cross-org domain ownership
- if EmailChannel.objects.filter(domain=domain).exclude(team__organization_id=team.organization_id).exists():
- return Response({"error": "This domain is already in use by another organization."}, status=409)
-
- # A verified sibling proves the organization already controls the sending domain.
- sibling = (
- EmailChannel.objects.filter(team__organization_id=team.organization_id, domain=domain)
- .order_by("-domain_verified", "created_at")
- .first()
- )
-
+ sibling: EmailChannel | None = None
dns_records: dict = {}
- if sibling:
- dns_records = sibling.dns_records
- else:
- try:
- dns_records = mailgun_add_domain(domain)
- except MailgunNotConfigured:
- logger.info("email_connect_mailgun_not_configured", team_id=team.id, domain=domain)
- return Response({"error": "Mailgun API key not configured"}, status=400)
- except MailgunDomainConflict as e:
- reclaimed = _try_reclaim_stranded_domain(team, domain)
- if reclaimed is None:
- logger.info("email_connect_mailgun_domain_conflict", team_id=team.id, domain=domain, error=str(e))
+ if kind == EmailChannelKind.SUPPORT:
+ if (
+ EmailChannel.objects.filter(domain=domain, kind=EmailChannelKind.SUPPORT)
+ .exclude(team__organization_id=team.organization_id)
+ .exists()
+ ):
+ return Response({"error": "This domain is already in use by another organization."}, status=409)
+
+ sibling = (
+ EmailChannel.objects.filter(
+ team__organization_id=team.organization_id,
+ domain=domain,
+ kind=EmailChannelKind.SUPPORT,
+ )
+ .order_by("-domain_verified", "created_at")
+ .first()
+ )
+ if sibling:
+ dns_records = sibling.dns_records
+ else:
+ try:
+ dns_records = mailgun_add_domain(domain)
+ except MailgunNotConfigured:
+ logger.info("email_connect_mailgun_not_configured", team_id=team.id, domain=domain)
+ return Response({"error": "Mailgun API key not configured"}, status=400)
+ except MailgunDomainConflict as e:
+ reclaimed = _try_reclaim_stranded_domain(team, domain)
+ if reclaimed is None:
+ logger.info(
+ "email_connect_mailgun_domain_conflict", team_id=team.id, domain=domain, error=str(e)
+ )
+ return Response(
+ {
+ "error": "This domain cannot be registered for sending. "
+ "It may already be claimed by another account."
+ },
+ status=400,
+ )
+ dns_records = reclaimed
+ except Exception:
+ logger.exception("email_connect_mailgun_add_domain_failed", team_id=team.id, domain=domain)
return Response(
- {
- "error": "This domain cannot be registered for sending. "
- "It may already be claimed by another account."
- },
- status=400,
+ {"error": "Failed to register domain for sending. Please try again later."},
+ status=502,
)
- dns_records = reclaimed
- except Exception:
- logger.exception("email_connect_mailgun_add_domain_failed", team_id=team.id, domain=domain)
- return Response(
- {"error": "Failed to register domain for sending. Please try again later."},
- status=502,
- )
config: EmailChannel | None = None
failure: Response | None = None
@@ -424,13 +519,36 @@ class EmailConnectView(APIView):
# Lock team row to serialize concurrent connects and enforce the config limit
Team.objects.select_for_update().get(id=team.id)
- current_count = EmailChannel.objects.filter(team=team, kind=kind).count()
+ if kind == EmailChannelKind.CUSTOMER_COMMUNICATION:
+ _release_expired_customer_email_reservation(from_email=from_email)
+
+ channels = EmailChannel.objects.filter(team=team, kind=kind)
+ if kind == EmailChannelKind.CUSTOMER_COMMUNICATION:
+ current_count = channels.exclude(
+ connection_status=EmailChannelConnectionStatus.CONFIRMATION_EXPIRED
+ ).count()
+ pending_owner_count = channels.filter(
+ owner=owner,
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ ).count()
+ else:
+ current_count = channels.count()
+ pending_owner_count = 0
+
max_channels = (
MAX_EMAIL_CONFIGS_PER_TEAM
if kind == EmailChannelKind.SUPPORT
else MAX_CUSTOMER_COMMUNICATION_CHANNELS_PER_TEAM
)
- if current_count >= max_channels:
+ if pending_owner_count >= MAX_PENDING_CUSTOMER_COMMUNICATION_CHANNELS_PER_OWNER:
+ failure = Response(
+ {
+ "error": f"You can have up to {MAX_PENDING_CUSTOMER_COMMUNICATION_CHANNELS_PER_OWNER} "
+ "email addresses awaiting confirmation. Finish or disconnect one before adding another."
+ },
+ status=400,
+ )
+ elif current_count >= max_channels:
channel_name = "support" if kind == EmailChannelKind.SUPPORT else "customer communication"
failure = Response(
{"error": f"Maximum of {max_channels} {channel_name} email addresses per team."},
@@ -448,16 +566,28 @@ class EmailConnectView(APIView):
dns_records=dns_records,
domain_verified=sibling.domain_verified if sibling else False,
is_default=kind == EmailChannelKind.SUPPORT and current_count == 0,
+ connection_status=(
+ EmailChannelConnectionStatus.ACTIVE
+ if kind == EmailChannelKind.SUPPORT
+ else EmailChannelConnectionStatus.PENDING_CONFIRMATION
+ ),
)
if kind == EmailChannelKind.SUPPORT:
_set_email_enabled(team, enabled=True)
+ else:
+ EmailChannelSetup.objects.for_team(team.id).create(
+ team=team,
+ channel=config,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() + CUSTOMER_EMAIL_SETUP_TTL,
+ )
except IntegrityError:
failure = Response({"error": "This email address is already connected."}, status=409)
if config is None:
# Failure responses are deferred to here so the Mailgun cleanup call
# doesn't run inside the atomic block while the team row is locked.
- if not sibling:
+ if kind == EmailChannelKind.SUPPORT and not sibling:
_release_domain_if_unused(team, domain)
assert failure is not None
return failure
@@ -644,13 +774,79 @@ class EmailSetDefaultView(APIView):
return Response({"ok": True})
+class EmailConfirmForwardingView(APIView):
+ permission_classes = [IsAuthenticated]
+
+ @extend_schema(
+ tags=["conversations"],
+ request=ConfigIdSerializer,
+ responses={
+ 200: EmailConfirmForwardingResponseSerializer,
+ 400: OpenApiResponse(response=EmailChannelErrorSerializer),
+ 404: OpenApiResponse(response=EmailChannelErrorSerializer),
+ },
+ )
+ def post(self, request: Request, *args, **kwargs) -> Response:
+ result = _get_team_from_request(request)
+ if isinstance(result, Response):
+ return result
+ user, team = result
+
+ id_serializer = ConfigIdSerializer(data=request.data)
+ id_serializer.is_valid(raise_exception=True)
+ config_id = id_serializer.validated_data["config_id"]
+
+ with transaction.atomic():
+ config = (
+ EmailChannel.objects.select_for_update()
+ .filter(
+ id=config_id,
+ team=team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=user,
+ )
+ .first()
+ )
+ if config is None:
+ return Response({"error": "Email config not found"}, status=404)
+ if config.connection_status != EmailChannelConnectionStatus.PENDING_CONFIRMATION:
+ return Response({"error": "This forwarding setup is not pending confirmation."}, status=400)
+
+ setup = EmailChannelSetup.objects.for_team(team.id).select_for_update().filter(channel=config).first()
+ if setup is None:
+ return Response({"error": "This forwarding setup is no longer available."}, status=400)
+ if setup.expires_at <= timezone.now():
+ setup.delete()
+ config.connection_status = EmailChannelConnectionStatus.CONFIRMATION_EXPIRED
+ config.save(update_fields=["connection_status"])
+ return Response({"error": "This forwarding setup expired. Add the email again to restart."}, status=400)
+ if not setup.confirmation_action:
+ return Response({"error": "Gmail has not sent a forwarding confirmation yet."}, status=400)
+
+ confirmation_url = setup.confirmation_action
+ # Google provides no completion callback, so the owner's request for this authenticated action is the activation boundary.
+ setup.delete()
+ config.connection_status = EmailChannelConnectionStatus.ACTIVE
+ config.save(update_fields=["connection_status"])
+
+ logger.info(
+ "customer_email_forwarding_confirmed",
+ team_id=team.id,
+ config_id=config.id,
+ user_id=user.id,
+ )
+ return Response({"ok": True, "confirmation_url": confirmation_url})
+
+
class EmailDisconnectView(APIView):
- permission_classes = [IsAuthenticated, IsConversationsAdmin]
+ permission_classes = [IsAuthenticated]
@extend_schema(
+ tags=["conversations"],
request=ConfigIdSerializer,
responses={
200: EmailChannelOperationResponseSerializer,
+ 403: OpenApiResponse(response=EmailChannelErrorSerializer),
404: OpenApiResponse(response=EmailChannelErrorSerializer),
},
)
@@ -672,11 +868,17 @@ class EmailDisconnectView(APIView):
# race another default change into the partial unique constraint
Team.objects.select_for_update().get(id=team.id)
config = EmailChannel.objects.filter(id=config_id, team=team).first()
+ is_admin = _is_organization_admin(user, team)
if not config:
+ return Response({"error": "Email config not found"}, status=404 if is_admin else 403)
+ if config.kind == EmailChannelKind.SUPPORT and not is_admin:
+ return Response({"error": "Only organization admins can manage support email channels."}, status=403)
+ if config.kind == EmailChannelKind.CUSTOMER_COMMUNICATION and config.owner_id != user.id and not is_admin:
return Response({"error": "Email config not found"}, status=404)
domain_to_delete = config.domain
was_default = config.is_default
+ was_support_channel = config.kind == EmailChannelKind.SUPPORT
config.delete()
# Keep a support fallback sender after its previous default is removed.
@@ -691,7 +893,13 @@ class EmailDisconnectView(APIView):
replacement.save(update_fields=["is_default"])
# Only delete from Mailgun if no other config (on any team) uses this domain
- if not EmailChannel.objects.filter(domain=domain_to_delete).exists():
+ if (
+ was_support_channel
+ and not EmailChannel.objects.filter(
+ domain=domain_to_delete,
+ kind=EmailChannelKind.SUPPORT,
+ ).exists()
+ ):
should_delete_from_mailgun = True
# The legacy setting controls support email, not customer communication capture.
diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.py
index de2bf683569e..1e0f298272ce 100644
--- a/products/conversations/backend/api/tests/test_email_endpoints.py
+++ b/products/conversations/backend/api/tests/test_email_endpoints.py
@@ -23,7 +23,14 @@ from products.conversations.backend.mailgun import (
MailgunPermanentError,
MailgunTransientError,
)
-from products.conversations.backend.models import EmailChannel, EmailChannelKind, EmailOutboxMessage
+from products.conversations.backend.models import (
+ EmailChannel,
+ EmailChannelConnectionStatus,
+ EmailChannelKind,
+ EmailChannelSetup,
+ EmailChannelSetupProvider,
+ EmailOutboxMessage,
+)
from products.conversations.backend.models.ticket import Ticket
@@ -173,6 +180,327 @@ class TestEmailChannelPermissions(BaseTest):
assert response.status_code == 200
assert [config["owner_id"] for config in response.json()["configs"]] == [self.user.id]
+ @patch("products.conversations.backend.api.email_settings.mailgun_add_domain")
+ @patch(
+ "products.conversations.backend.api.email_settings.get_instance_setting",
+ return_value="mg.posthog.com",
+ )
+ def test_member_can_connect_and_disconnect_own_customer_channel_without_mailgun(
+ self, _mock_setting: MagicMock, mock_mailgun_add_domain: MagicMock
+ ) -> None:
+ connect_response = self.client.post(
+ "/api/conversations/v1/email/connect",
+ {
+ "from_email": self.user.email,
+ "from_name": self.user.email,
+ "kind": EmailChannelKind.CUSTOMER_COMMUNICATION,
+ "owner_id": self.user.id,
+ },
+ content_type="application/json",
+ )
+
+ assert connect_response.status_code == 200
+ channel = EmailChannel.objects.get(team=self.team)
+ assert channel.owner_id == self.user.id
+ assert channel.domain_verified is False
+ assert channel.dns_records == {}
+ assert channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION
+ setup = EmailChannelSetup.objects.for_team(self.team.id).get(channel=channel)
+ assert setup.provider == EmailChannelSetupProvider.GOOGLE
+ assert setup.expires_at > timezone.now()
+ assert setup.confirmation_action is None
+ assert connect_response.json()["config"]["connection_status"] == "pending_confirmation"
+ assert connect_response.json()["config"]["confirmation_available"] is False
+ mock_mailgun_add_domain.assert_not_called()
+
+ disconnect_response = self.client.post(
+ "/api/conversations/v1/email/disconnect",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert disconnect_response.status_code == 200
+ assert not EmailChannel.objects.filter(id=channel.id).exists()
+
+ def test_owner_consumes_confirmation_action_and_activates_channel(self) -> None:
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="pending-token",
+ from_email=self.user.email,
+ from_name=self.user.email,
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+ setup = EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() + timedelta(hours=1),
+ confirmation_action="https://mail-settings.google.com/mail/vf-confirmation",
+ confirmation_received_at=timezone.now(),
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/confirm-forwarding",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {
+ "ok": True,
+ "confirmation_url": "https://mail-settings.google.com/mail/vf-confirmation",
+ }
+ channel.refresh_from_db()
+ assert channel.connection_status == EmailChannelConnectionStatus.ACTIVE
+ assert not EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+
+ def test_non_owner_cannot_consume_confirmation_action(self) -> None:
+ owner = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(
+ organization=self.organization,
+ user=owner,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=owner,
+ inbound_token="other-pending-token",
+ from_email=owner.email,
+ from_name=owner.email,
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+ setup = EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() + timedelta(hours=1),
+ confirmation_action="https://mail-settings.google.com/mail/vf-other",
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/confirm-forwarding",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 404
+ assert EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+ channel.refresh_from_db()
+ assert channel.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION
+
+ def test_status_expires_pending_setup(self) -> None:
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="expired-token",
+ from_email=self.user.email,
+ from_name=self.user.email,
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+ setup = EmailChannelSetup.objects.for_team(self.team.id).create(
+ team=self.team,
+ channel=channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() - timedelta(seconds=1),
+ confirmation_action="https://mail-settings.google.com/mail/vf-expired",
+ )
+
+ response = self.client.get(f"/api/conversations/v1/email/status?kind={EmailChannelKind.CUSTOMER_COMMUNICATION}")
+
+ assert response.status_code == 200
+ assert response.json()["configs"][0]["connection_status"] == "confirmation_expired"
+ assert response.json()["configs"][0]["confirmation_available"] is False
+ assert not EmailChannelSetup.objects.for_team(self.team.id).filter(id=setup.id).exists()
+
+ @parameterized.expand(
+ [
+ ("pending_with_expired_setup", EmailChannelConnectionStatus.PENDING_CONFIRMATION, True),
+ ("confirmation_expired", EmailChannelConnectionStatus.CONFIRMATION_EXPIRED, False),
+ ]
+ )
+ @patch(
+ "products.conversations.backend.api.email_settings.get_instance_setting",
+ return_value="mg.posthog.com",
+ )
+ def test_connect_releases_expired_customer_email_reservation(
+ self,
+ _name: str,
+ connection_status: str,
+ create_setup: bool,
+ _mock_setting: MagicMock,
+ ) -> None:
+ other_organization = Organization.objects.create(name="Other organization")
+ other_team = Team.objects.create(organization=other_organization)
+ other_owner = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(
+ organization=other_organization,
+ user=other_owner,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+ stale_channel = EmailChannel.objects.create(
+ team=other_team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=other_owner,
+ inbound_token="stale-token",
+ from_email="[email protected]",
+ from_name="Reserved",
+ domain="example.com",
+ connection_status=connection_status,
+ )
+ if create_setup:
+ EmailChannelSetup.objects.for_team(other_team.id).create(
+ team=other_team,
+ channel=stale_channel,
+ provider=EmailChannelSetupProvider.GOOGLE,
+ expires_at=timezone.now() - timedelta(seconds=1),
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/connect",
+ {
+ "from_email": "[email protected]",
+ "from_name": "Customer success",
+ "kind": EmailChannelKind.CUSTOMER_COMMUNICATION,
+ "owner_id": self.user.id,
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ assert not EmailChannel.objects.filter(id=stale_channel.id).exists()
+ replacement = EmailChannel.objects.get(team=self.team, from_email="[email protected]")
+ assert replacement.owner_id == self.user.id
+ assert replacement.connection_status == EmailChannelConnectionStatus.PENDING_CONFIRMATION
+
+ @patch(
+ "products.conversations.backend.api.email_settings.MAX_PENDING_CUSTOMER_COMMUNICATION_CHANNELS_PER_OWNER",
+ 1,
+ )
+ @patch(
+ "products.conversations.backend.api.email_settings.get_instance_setting",
+ return_value="mg.posthog.com",
+ )
+ def test_member_cannot_exhaust_team_quota_with_pending_channels(self, _mock_setting: MagicMock) -> None:
+ EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="pending-token",
+ from_email="[email protected]",
+ from_name="Pending",
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.PENDING_CONFIRMATION,
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/connect",
+ {
+ "from_email": "[email protected]",
+ "from_name": "Another address",
+ "kind": EmailChannelKind.CUSTOMER_COMMUNICATION,
+ "owner_id": self.user.id,
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == 400
+ assert "awaiting confirmation" in response.json()["error"]
+ assert EmailChannel.objects.filter(team=self.team).count() == 1
+
+ @patch("products.conversations.backend.api.email_settings.MAX_CUSTOMER_COMMUNICATION_CHANNELS_PER_TEAM", 1)
+ @patch(
+ "products.conversations.backend.api.email_settings.get_instance_setting",
+ return_value="mg.posthog.com",
+ )
+ def test_expired_customer_channels_do_not_count_toward_team_limit(self, _mock_setting: MagicMock) -> None:
+ EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=self.user,
+ inbound_token="expired-token-for-limit",
+ from_email="[email protected]",
+ from_name="Expired",
+ domain="example.com",
+ connection_status=EmailChannelConnectionStatus.CONFIRMATION_EXPIRED,
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/connect",
+ {
+ "from_email": "[email protected]",
+ "from_name": "New address",
+ "kind": EmailChannelKind.CUSTOMER_COMMUNICATION,
+ "owner_id": self.user.id,
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ assert EmailChannel.objects.filter(team=self.team).count() == 2
+
+ @patch("products.conversations.backend.api.email_settings.mailgun_add_domain")
+ @patch(
+ "products.conversations.backend.api.email_settings.get_instance_setting",
+ return_value="mg.posthog.com",
+ )
+ def test_member_cannot_connect_customer_channel_for_another_owner(
+ self, _mock_setting: MagicMock, mock_mailgun_add_domain: MagicMock
+ ) -> None:
+ other_owner = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(
+ organization=self.organization,
+ user=other_owner,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/connect",
+ {
+ "from_email": other_owner.email,
+ "from_name": other_owner.email,
+ "kind": EmailChannelKind.CUSTOMER_COMMUNICATION,
+ "owner_id": other_owner.id,
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == 403
+ assert not EmailChannel.objects.filter(team=self.team).exists()
+ mock_mailgun_add_domain.assert_not_called()
+
+ def test_member_cannot_disconnect_another_owners_customer_channel(self) -> None:
+ other_owner = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(
+ organization=self.organization,
+ user=other_owner,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+ channel = EmailChannel.objects.create(
+ team=self.team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=other_owner,
+ inbound_token="other-owner-token",
+ from_email=other_owner.email,
+ from_name=other_owner.email,
+ domain="example.com",
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/disconnect",
+ {"config_id": str(channel.id)},
+ content_type="application/json",
+ )
+
+ assert response.status_code == 404
+ assert EmailChannel.objects.filter(id=channel.id).exists()
+
@patch("products.conversations.backend.api.email_settings.send_mime")
def test_member_cannot_send_test_from_another_owners_channel(self, mock_send_mime: MagicMock) -> None:
other_owner = User.objects.create(email="[email protected]")
@@ -574,6 +902,47 @@ class TestEmailMultiConfig(BaseTest):
self.team.refresh_from_db()
assert (self.team.conversations_settings or {}).get("email_enabled") is not True
+ @patch("products.conversations.backend.api.email_settings.mailgun_add_domain")
+ @patch(
+ "products.conversations.backend.api.email_settings.get_instance_setting",
+ return_value="mg.posthog.com",
+ )
+ def test_customer_channel_allows_shared_email_domain_across_organizations(
+ self, _mock_setting: MagicMock, mock_mailgun: MagicMock
+ ) -> None:
+ other_org = Organization.objects.create(name="Other Org")
+ other_team = Team.objects.create(organization=other_org)
+ other_owner = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(
+ user=other_owner,
+ organization=other_org,
+ level=OrganizationMembership.Level.MEMBER,
+ )
+ EmailChannel.objects.create(
+ team=other_team,
+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,
+ owner=other_owner,
+ inbound_token="other-customer-token",
+ from_email=other_owner.email,
+ from_name="Other owner",
+ domain="gmail.com",
+ )
+
+ response = self.client.post(
+ "/api/conversations/v1/email/connect",
+ {
+ "from_email": "[email protected]",
+ "from_name": "Customer success",
+ "kind": EmailChannelKind.CUSTOMER_COMMUNICATION,
+ "owner_id": self.user.id,
+ },
+ content_type="application/json",
+ )
+
+ assert response.status_code == 200
+ assert EmailChannel.objects.filter(team=self.team, from_email="[email protected]").exists()
+ mock_mailgun.assert_not_called()
+
@patch("products.conversations.backend.api.email_settings.mailgun_add_domain")
@patch(
"products.conversations.backend.api.email_settings.get_instance_setting",
@@ -603,7 +972,7 @@ class TestEmailMultiConfig(BaseTest):
"products.conversations.backend.api.email_settings.get_instance_setting",
return_value="mg.posthog.com",
)
- def test_customer_channel_reuses_verified_support_domain(
+ def test_customer_channel_does_not_use_support_sending_domain(
self, _mock_setting: MagicMock, mock_mailgun: MagicMock
) -> None:
EmailChannel.objects.create(
@@ -630,8 +999,8 @@ class TestEmailMultiConfig(BaseTest):
assert response.status_code == 200
customer_channel = EmailChannel.objects.get(kind=EmailChannelKind.CUSTOMER_COMMUNICATION)
- assert customer_channel.domain_verified is True
- assert customer_channel.dns_records == {"sending_dns_records": [{"record_type": "TXT", "value": "verified"}]}
+ assert customer_channel.domain_verified is False
+ assert customer_channel.dns_records == {}
mock_mailgun.assert_not_called()
@patch(
diff --git a/products/conversations/backend/api/urls.py b/products/conversations/backend/api/urls.py
index 619efa7326de..51d9becafade 100644
--- a/products/conversations/backend/api/urls.py
+++ b/products/conversations/backend/api/urls.py
@@ -4,6 +4,7 @@ from django.urls import path, re_path
from .email_events import email_inbound_handler
from .email_settings import (
+ EmailConfirmForwardingView,
EmailConnectView,
EmailDisconnectView,
EmailSendTestView,
@@ -57,6 +58,11 @@ urlpatterns = [
re_path(r"^v1/email/inbound/?$", email_inbound_handler, name="email-inbound"),
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(
+ r"^v1/email/confirm-forwarding/?$",
+ EmailConfirmForwardingView.as_view(),
+ name="email-confirm-forwarding",
+ ),
re_path(r"^v1/email/disconnect/?$", EmailDisconnectView.as_view(), name="email-disconnect"),
re_path(r"^v1/email/set-default/?$", EmailSetDefaultView.as_view(), name="email-set-default"),
re_path(r"^v1/email/verify-domain/?$", EmailVerifyDomainView.as_view(), name="email-verify-domain"),
diff --git a/products/conversations/backend/models/team_conversations_email_config.py b/products/conversations/backend/models/team_conversations_email_config.py
index 944bf0c162b6..8d1baacbbb62 100644
--- a/products/conversations/backend/models/team_conversations_email_config.py
+++ b/products/conversations/backend/models/team_conversations_email_config.py
@@ -5,6 +5,7 @@ from posthog.models.utils import UUIDModel
MAX_EMAIL_CONFIGS_PER_TEAM = 10
MAX_CUSTOMER_COMMUNICATION_CHANNELS_PER_TEAM = 100
+MAX_PENDING_CUSTOMER_COMMUNICATION_CHANNELS_PER_OWNER = 5
class EmailChannelKind(models.TextChoices):
diff --git a/products/conversations/frontend/components/EmailForwardingAddress.tsx b/products/conversations/frontend/components/EmailForwardingAddress.tsx
new file mode 100644
index 000000000000..a94285d2ee60
--- /dev/null
+++ b/products/conversations/frontend/components/EmailForwardingAddress.tsx
@@ -0,0 +1,36 @@
+import { IconCopy } from '@posthog/icons'
+import { LemonButton, LemonLabel } from '@posthog/lemon-ui'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+export function EmailForwardingAddress({ forwardingAddress }: { forwardingAddress: string }): JSX.Element {
+ return (
+ <div>
+ <LemonLabel>Forwarding address</LemonLabel>
+ <p className="text-xs text-muted-alt mb-1">
+ Forward incoming emails to this address in your email provider.
+ </p>
+ <div className="flex items-center gap-2">
+ <code className="bg-surface-primary px-2 py-1 rounded text-sm break-all">{forwardingAddress}</code>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconCopy />}
+ tooltip="Copy forwarding address"
+ onClick={() => {
+ void navigator.clipboard.writeText(forwardingAddress)
+ lemonToast.success('Forwarding address copied')
+ }}
+ />
+ </div>
+ <div className="text-xs text-muted-alt mt-2 flex flex-col gap-0.5">
+ <p className="mb-0">
+ <strong>Gmail:</strong> Settings → Forwarding → Add a forwarding address
+ </p>
+ <p className="mb-0">
+ <strong>Outlook:</strong> Settings → Mail → Forwarding → Enable forwarding
+ </p>
+ </div>
+ </div>
+ )
+}
diff --git a/products/conversations/frontend/scenes/settings/EmailSection.tsx b/products/conversations/frontend/scenes/settings/EmailSection.tsx
index cf137654b9ab..0a8b5cd46f39 100644
--- a/products/conversations/frontend/scenes/settings/EmailSection.tsx
+++ b/products/conversations/frontend/scenes/settings/EmailSection.tsx
@@ -1,16 +1,16 @@
import { useActions, useValues } from 'kea'
import { useState } from 'react'
-import { IconCopy, IconPlus, IconRefresh } from '@posthog/icons'
+import { IconPlus, IconRefresh } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonCard, LemonCollapse, LemonInput, LemonTag } from '@posthog/lemon-ui'
import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
import { OrganizationMembershipLevel } from 'lib/constants'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
-import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { SceneSection } from '~/layout/scenes/components/SceneSection'
+import { EmailForwardingAddress } from '../../components/EmailForwardingAddress'
import { EmailConfigStatus, supportSettingsLogic } from './supportSettingsLogic'
interface DnsRecord {
@@ -77,37 +77,7 @@ function EmailConfigContent({ config }: { config: EmailConfigStatus }): JSX.Elem
return (
<div className="flex flex-col gap-3 p-3">
- {/* Forwarding address */}
- {config.forwarding_address && (
- <div>
- <label className="font-medium text-sm">Forwarding address</label>
- <p className="text-xs text-muted-alt mb-1">
- Forward incoming emails to this address in your email provider.
- </p>
- <div className="flex items-center gap-2">
- <code className="bg-surface-primary px-2 py-1 rounded text-sm break-all">
- {config.forwarding_address}
- </code>
- <LemonButton
- type="secondary"
- size="small"
- icon={<IconCopy />}
- onClick={() => {
- void navigator.clipboard.writeText(config.forwarding_address!)
- lemonToast.success('Copied to clipboard')
- }}
- />
- </div>
- <div className="text-xs text-muted-alt mt-2 flex flex-col gap-0.5">
- <p className="mb-0">
- <strong>Gmail:</strong> Settings → Forwarding → Add a forwarding address
- </p>
- <p className="mb-0">
- <strong>Outlook:</strong> Settings → Mail → Forwarding → Enable forwarding
- </p>
- </div>
- </div>
- )}
+ {config.forwarding_address && <EmailForwardingAddress forwardingAddress={config.forwarding_address} />}
{/* Domain verification */}
<div>
diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
index 40c537315f39..76acf4bbe81c 100644
--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.ts
@@ -39,6 +39,9 @@ export interface EmailConfigStatus {
domain_verified: boolean
dns_records: Record<string, any> | null
is_default: boolean
+ connection_status: 'pending_confirmation' | 'active' | 'confirmation_expired'
+ setup_expires_at: string | null
+ confirmation_available: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx
new file mode 100644
index 000000000000..61762ba34405
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/CustomerEmailConfig.tsx
@@ -0,0 +1,210 @@
+import { useActions, useValues } from 'kea'
+
+import { IconCheck, IconPlus, IconRefresh, IconTrash } from '@posthog/icons'
+import {
+ LemonBanner,
+ LemonButton,
+ LemonCard,
+ LemonCollapse,
+ LemonInput,
+ LemonLabel,
+ LemonSkeleton,
+ LemonTag,
+} from '@posthog/lemon-ui'
+
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+
+import { EmailForwardingAddress } from 'products/conversations/frontend/components/EmailForwardingAddress'
+
+import { customerEmailConfigLogic } from './customerEmailConfigLogic'
+import type { CustomerEmailChannel } from './customerEmailConfigLogic'
+
+function ConnectedEmailContent({ channel }: { channel: CustomerEmailChannel }): JSX.Element {
+ const { channelsLoading, confirmingChannelId, disconnectingChannelId } = useValues(customerEmailConfigLogic)
+ const { confirmForwarding, disconnectEmail, loadChannels } = useActions(customerEmailConfigLogic)
+
+ return (
+ <div className="flex flex-col gap-3 p-3">
+ {channel.connection_status !== 'confirmation_expired' &&
+ (channel.forwarding_address ? (
+ <EmailForwardingAddress forwardingAddress={channel.forwarding_address} />
+ ) : (
+ <p className="mb-0 text-sm text-secondary">
+ A forwarding address is not available. Ask your PostHog administrator to configure the inbound
+ email domain.
+ </p>
+ ))}
+ {channel.connection_status === 'pending_confirmation' &&
+ (channel.confirmation_available ? (
+ <LemonBanner type="success">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span>Gmail sent a forwarding confirmation. Open it to finish connecting this email.</span>
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconCheck />}
+ loading={confirmingChannelId === channel.id}
+ disabledReason={
+ confirmingChannelId && confirmingChannelId !== channel.id
+ ? 'Another email confirmation is opening'
+ : undefined
+ }
+ onClick={() => confirmForwarding(channel.id)}
+ >
+ Verify forwarding
+ </LemonButton>
+ </div>
+ </LemonBanner>
+ ) : (
+ <LemonBanner type="info">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <span>Waiting for Gmail to send the forwarding confirmation.</span>
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={<IconRefresh />}
+ loading={channelsLoading}
+ onClick={loadChannels}
+ >
+ Check again
+ </LemonButton>
+ </div>
+ </LemonBanner>
+ ))}
+ {channel.connection_status === 'confirmation_expired' && (
+ <LemonBanner type="error">
+ This forwarding setup expired. Disconnect this email and add it again to restart setup.
+ </LemonBanner>
+ )}
+ <div className="flex justify-end border-t pt-2">
+ <LemonButton
+ type="secondary"
+ status="danger"
+ size="small"
+ icon={<IconTrash />}
+ loading={disconnectingChannelId === channel.id}
+ disabledReason={disconnectingChannelId ? 'Another email is being disconnected' : undefined}
+ onClick={() => {
+ LemonDialog.open({
+ title: `Disconnect ${channel.from_email}?`,
+ description: 'New messages sent to this email will stop appearing on customer accounts.',
+ primaryButton: {
+ children: 'Disconnect',
+ status: 'danger',
+ onClick: () => disconnectEmail(channel.id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }}
+ >
+ Disconnect
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
+
+function connectedEmailHeader(channel: CustomerEmailChannel): JSX.Element {
+ const status =
+ channel.connection_status === 'active'
+ ? { label: 'Connected', type: 'success' as const }
+ : channel.connection_status === 'confirmation_expired'
+ ? { label: 'Setup expired', type: 'danger' as const }
+ : { label: 'Setup pending', type: 'warning' as const }
+ return (
+ <div className="flex min-w-0 items-center gap-2 text-left">
+ <span className="truncate font-medium">{channel.from_email}</span>
+ <LemonTag type={status.type} size="small" className="shrink-0">
+ {status.label}
+ </LemonTag>
+ </div>
+ )
+}
+
+function AddEmailForm(): JSX.Element {
+ const { addEmailFormVisible, connecting, emailDraft } = useValues(customerEmailConfigLogic)
+ const { connectEmail, setAddEmailFormVisible, setEmailDraft } = useActions(customerEmailConfigLogic)
+
+ if (!addEmailFormVisible) {
+ return (
+ <LemonButton type="secondary" size="small" icon={<IconPlus />} onClick={() => setAddEmailFormVisible(true)}>
+ Add email address
+ </LemonButton>
+ )
+ }
+
+ return (
+ <LemonCard hoverEffect={false} className="flex flex-col gap-2 px-4 py-3">
+ <LemonLabel>Connect new email</LemonLabel>
+ <p className="mb-0 text-sm text-secondary">
+ Enter the email address you use to talk to customers. After connecting it, forward incoming messages to
+ the PostHog address shown here.
+ </p>
+ <LemonInput
+ type="email"
+ value={emailDraft}
+ onChange={setEmailDraft}
+ placeholder="[email protected]"
+ fullWidth
+ disabled={connecting}
+ onPressEnter={connectEmail}
+ />
+ <div className="flex gap-2">
+ <LemonButton
+ type="primary"
+ size="small"
+ loading={connecting}
+ disabledReason={emailDraft.trim() ? undefined : 'Enter your email address'}
+ onClick={connectEmail}
+ >
+ Connect email
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ size="small"
+ disabled={connecting}
+ onClick={() => setAddEmailFormVisible(false)}
+ >
+ Cancel
+ </LemonButton>
+ </div>
+ </LemonCard>
+ )
+}
+
+export function CustomerEmailConfig(): JSX.Element {
+ const { channels, channelsLoadFailed, channelsLoading, expandedChannelIds } = useValues(customerEmailConfigLogic)
+ const { loadChannels, setExpandedChannelIds } = useActions(customerEmailConfigLogic)
+
+ if (channelsLoading && channels.length === 0) {
+ return <LemonSkeleton className="h-32 max-w-2xl" />
+ }
+ if (channelsLoadFailed && channels.length === 0) {
+ return (
+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadChannels }}>
+ Could not load your connected emails.
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <div className="flex max-w-2xl flex-col gap-3">
+ {channels.length > 0 && (
+ <LemonCollapse
+ className="bg-surface-primary"
+ multiple
+ activeKeys={expandedChannelIds}
+ onChange={setExpandedChannelIds}
+ panels={channels.map((channel) => ({
+ key: channel.id,
+ header: connectedEmailHeader(channel),
+ content: <ConnectedEmailContent channel={channel} />,
+ }))}
+ />
+ )}
+ <div className="flex">
+ <AddEmailForm />
+ </div>
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts
new file mode 100644
index 000000000000..204774460d05
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.test.ts
@@ -0,0 +1,121 @@
+import { expectLogic } from 'kea-test-utils'
+
+import api from 'lib/api'
+import { userLogic } from 'scenes/userLogic'
+
+import { initKeaTests } from '~/test/init'
+import { UserType } from '~/types'
+
+import { customerEmailConfigLogic } from './customerEmailConfigLogic'
+import type { CustomerEmailChannel } from './customerEmailConfigLogic'
+
+describe('customerEmailConfigLogic', () => {
+ let logic: ReturnType<typeof customerEmailConfigLogic.build>
+ let getSpy: jest.SpyInstance
+ let createSpy: jest.SpyInstance
+
+ const channel: CustomerEmailChannel = {
+ id: 'channel-1',
+ from_email: '[email protected]',
+ forwarding_address: '[email protected]',
+ connection_status: 'pending_confirmation',
+ setup_expires_at: '2026-08-13T12:00:00Z',
+ confirmation_available: false,
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ jest.resetAllMocks()
+ userLogic.actions.loadUserSuccess({
+ id: 7,
+ email: '[email protected]',
+ first_name: 'Casey',
+ last_name: 'Manager',
+ } as UserType)
+ getSpy = jest.spyOn(api, 'get').mockResolvedValue({ configs: [] })
+ createSpy = jest.spyOn(api, 'create')
+ logic = customerEmailConfigLogic()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('loads only customer communication channels', async () => {
+ getSpy.mockResolvedValue({ configs: [channel] })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(getSpy).toHaveBeenCalledWith('api/conversations/v1/email/status?kind=customer_communication')
+ expect(logic.values.channels).toEqual([channel])
+ expect(logic.values.channelsLoading).toBe(false)
+ })
+
+ it('opens an authenticated confirmation and activates the channel', async () => {
+ const replace = jest.fn()
+ jest.spyOn(window, 'open').mockReturnValue({
+ opener: window,
+ location: { replace },
+ close: jest.fn(),
+ } as unknown as Window)
+ getSpy.mockResolvedValue({
+ configs: [{ ...channel, confirmation_available: true }],
+ })
+ createSpy.mockResolvedValue({
+ ok: true,
+ confirmation_url: 'https://mail-settings.google.com/mail/vf-confirmation',
+ })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.confirmForwarding(channel.id)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenCalledWith('api/conversations/v1/email/confirm-forwarding', {
+ config_id: channel.id,
+ })
+ expect(window.open).toHaveBeenCalledWith('about:blank', '_blank')
+ expect(replace).toHaveBeenCalledWith('https://mail-settings.google.com/mail/vf-confirmation')
+ expect(logic.values.channels[0]).toEqual({
+ ...channel,
+ connection_status: 'active',
+ setup_expires_at: null,
+ confirmation_available: false,
+ })
+ expect(logic.values.confirmingChannelId).toBeNull()
+ })
+
+ it('connects and disconnects the current user email', async () => {
+ createSpy.mockResolvedValueOnce({ config: channel }).mockResolvedValueOnce({ ok: true })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.addEmailFormVisible).toBe(false)
+ logic.actions.setAddEmailFormVisible(true)
+ logic.actions.setEmailDraft(' [email protected] ')
+ logic.actions.connectEmail()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenNthCalledWith(1, 'api/conversations/v1/email/connect', {
+ from_email: '[email protected]',
+ from_name: 'Casey Manager',
+ kind: 'customer_communication',
+ owner_id: 7,
+ })
+ expect(logic.values.channels).toEqual([channel])
+ expect(logic.values.emailDraft).toBe('')
+ expect(logic.values.addEmailFormVisible).toBe(false)
+ expect(logic.values.connecting).toBe(false)
+ expect(logic.values.expandedChannelIds).toEqual([channel.id])
+
+ logic.actions.disconnectEmail(channel.id)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(createSpy).toHaveBeenNthCalledWith(2, 'api/conversations/v1/email/disconnect', {
+ config_id: channel.id,
+ })
+ expect(logic.values.channels).toEqual([])
+ expect(logic.values.expandedChannelIds).toEqual([])
+ expect(logic.values.disconnectingChannelId).toBeNull()
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts
new file mode 100644
index 000000000000..3e3da9041afa
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsConfigurationScene/email/customerEmailConfigLogic.ts
@@ -0,0 +1,264 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import posthog from 'posthog-js'
+
+import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { userLogic } from 'scenes/userLogic'
+
+import type { EmailConfigStatus } from 'products/conversations/frontend/scenes/settings/supportSettingsLogic'
+
+import type { UserType } from '../../../../../../frontend/src/types'
+
+export type CustomerEmailChannel = Pick<
+ EmailConfigStatus,
+ 'id' | 'from_email' | 'forwarding_address' | 'connection_status' | 'setup_expires_at' | 'confirmation_available'
+>
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface customerEmailConfigLogicValues {
+ user: UserType | null // userLogic
+ addEmailFormVisible: boolean
+ channels: CustomerEmailChannel[]
+ channelsLoadFailed: boolean
+ channelsLoading: boolean
+ confirmingChannelId: string | null
+ connecting: boolean
+ disconnectingChannelId: string | null
+ emailDraft: string
+ expandedChannelIds: string[]
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface customerEmailConfigLogicActions {
+ confirmForwarding: (channelId: string) => {
+ channelId: string
+ }
+ confirmForwardingFailure: () => {
+ value: true
+ }
+ confirmForwardingSuccess: (channelId: string) => {
+ channelId: string
+ }
+ connectEmail: () => {
+ value: true
+ }
+ connectEmailFailure: () => {
+ value: true
+ }
+ connectEmailSuccess: (channel: CustomerEmailChannel) => {
+ channel: CustomerEmailChannel
+ }
+ disconnectEmail: (channelId: string) => {
+ channelId: string
+ }
+ disconnectEmailFailure: () => {
+ value: true
+ }
+ disconnectEmailSuccess: (channelId: string) => {
+ channelId: string
+ }
+ loadChannels: () => {
+ value: true
+ }
+ loadChannelsFailure: () => {
+ value: true
+ }
+ loadChannelsSuccess: (channels: CustomerEmailChannel[]) => {
+ channels: CustomerEmailChannel[]
+ }
+ setAddEmailFormVisible: (visible: boolean) => {
+ visible: boolean
+ }
+ setEmailDraft: (email: string) => {
+ email: string
+ }
+ setExpandedChannelIds: (channelIds: string[]) => {
+ channelIds: string[]
+ }
+}
+
+export type customerEmailConfigLogicType = MakeLogicType<
+ customerEmailConfigLogicValues,
+ customerEmailConfigLogicActions
+>
+
+export const customerEmailConfigLogic = kea<customerEmailConfigLogicType>([
+ path(['scenes', 'customerAnalytics', 'configuration', 'customerEmailConfigLogic']),
+ connect(() => ({
+ values: [userLogic, ['user']],
+ })),
+ actions({
+ setAddEmailFormVisible: (visible: boolean) => ({ visible }),
+ setEmailDraft: (email: string) => ({ email }),
+ setExpandedChannelIds: (channelIds: string[]) => ({ channelIds }),
+ loadChannels: true,
+ loadChannelsSuccess: (channels: CustomerEmailChannel[]) => ({ channels }),
+ loadChannelsFailure: true,
+ connectEmail: true,
+ connectEmailSuccess: (channel: CustomerEmailChannel) => ({ channel }),
+ connectEmailFailure: true,
+ confirmForwarding: (channelId: string) => ({ channelId }),
+ confirmForwardingSuccess: (channelId: string) => ({ channelId }),
+ confirmForwardingFailure: true,
+ disconnectEmail: (channelId: string) => ({ channelId }),
+ disconnectEmailSuccess: (channelId: string) => ({ channelId }),
+ disconnectEmailFailure: true,
+ }),
+ reducers({
+ addEmailFormVisible: [
+ false,
+ {
+ setAddEmailFormVisible: (_, { visible }) => visible,
+ connectEmailSuccess: () => false,
+ },
+ ],
+ expandedChannelIds: [
+ [] as string[],
+ {
+ setExpandedChannelIds: (_, { channelIds }) => channelIds,
+ connectEmailSuccess: (state, { channel }) => [...state, channel.id],
+ disconnectEmailSuccess: (state, { channelId }) => state.filter((id) => id !== channelId),
+ },
+ ],
+ emailDraft: [
+ '',
+ {
+ setEmailDraft: (_, { email }) => email,
+ connectEmailSuccess: () => '',
+ },
+ ],
+ channels: [
+ [] as CustomerEmailChannel[],
+ {
+ loadChannelsSuccess: (_, { channels }) => channels,
+ connectEmailSuccess: (state, { channel }) => [...state, channel],
+ confirmForwardingSuccess: (state, { channelId }) =>
+ state.map((channel) =>
+ channel.id === channelId
+ ? {
+ ...channel,
+ connection_status: 'active',
+ setup_expires_at: null,
+ confirmation_available: false,
+ }
+ : channel
+ ),
+ disconnectEmailSuccess: (state, { channelId }) => state.filter((channel) => channel.id !== channelId),
+ },
+ ],
+ channelsLoading: [
+ true,
+ {
+ loadChannels: () => true,
+ loadChannelsSuccess: () => false,
+ loadChannelsFailure: () => false,
+ },
+ ],
+ channelsLoadFailed: [
+ false,
+ {
+ loadChannels: () => false,
+ loadChannelsSuccess: () => false,
+ loadChannelsFailure: () => true,
+ },
+ ],
+ connecting: [
+ false,
+ {
+ connectEmail: () => true,
+ connectEmailSuccess: () => false,
+ connectEmailFailure: () => false,
+ },
+ ],
+ confirmingChannelId: [
+ null as string | null,
+ {
+ confirmForwarding: (_, { channelId }) => channelId,
+ confirmForwardingSuccess: () => null,
+ confirmForwardingFailure: () => null,
+ },
+ ],
+ disconnectingChannelId: [
+ null as string | null,
+ {
+ disconnectEmail: (_, { channelId }) => channelId,
+ disconnectEmailSuccess: () => null,
+ disconnectEmailFailure: () => null,
+ },
+ ],
+ }),
+ listeners(({ actions, values }) => ({
+ loadChannels: async () => {
+ try {
+ // nosemgrep: prefer-codegen-api
+ const response = await api.get('api/conversations/v1/email/status?kind=customer_communication')
+ actions.loadChannelsSuccess(response.configs ?? [])
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.loadChannels' })
+ actions.loadChannelsFailure()
+ lemonToast.error('Could not refresh your connected emails. Try again.')
+ }
+ },
+ connectEmail: async () => {
+ const email = values.emailDraft.trim().toLowerCase()
+ if (!email || !values.user) {
+ actions.connectEmailFailure()
+ return
+ }
+ const displayName =
+ [values.user.first_name, values.user.last_name].filter(Boolean).join(' ').trim() || values.user.email
+ try {
+ // nosemgrep: prefer-codegen-api
+ const response = await api.create('api/conversations/v1/email/connect', {
+ from_email: email,
+ from_name: displayName,
+ kind: 'customer_communication',
+ owner_id: values.user.id,
+ })
+ actions.connectEmailSuccess(response.config)
+ lemonToast.success('Forwarding setup started')
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.connectEmail' })
+ actions.connectEmailFailure()
+ lemonToast.error('Could not connect this email. Check the address and try again.')
+ }
+ },
+ confirmForwarding: async ({ channelId }) => {
+ const confirmationWindow = window.open('about:blank', '_blank')
+ try {
+ // nosemgrep: prefer-codegen-api
+ const response = await api.create('api/conversations/v1/email/confirm-forwarding', {
+ config_id: channelId,
+ })
+ actions.confirmForwardingSuccess(channelId)
+ if (confirmationWindow) {
+ confirmationWindow.opener = null
+ confirmationWindow.location.replace(response.confirmation_url)
+ } else {
+ window.location.assign(response.confirmation_url)
+ }
+ lemonToast.success('Gmail confirmation opened')
+ } catch (error) {
+ confirmationWindow?.close()
+ posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.confirmForwarding' })
+ actions.confirmForwardingFailure()
+ lemonToast.error('Could not confirm forwarding. Check the setup and try again.')
+ }
+ },
+ disconnectEmail: async ({ channelId }) => {
+ try {
+ // nosemgrep: prefer-codegen-api
+ await api.create('api/conversations/v1/email/disconnect', { config_id: channelId })
+ actions.disconnectEmailSuccess(channelId)
+ lemonToast.success('Email disconnected')
+ } catch (error) {
+ posthog.captureException(error as Error, { scope: 'customerEmailConfigLogic.disconnectEmail' })
+ actions.disconnectEmailFailure()
+ lemonToast.error('Could not disconnect this email. Try again.')
+ }
+ },
+ })),
+ afterMount(({ actions }) => {
+ actions.loadChannels()
+ }),
+])