: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(conversations): add customer communication email channels (#80672)
Arthur Moreira de Deus51bf6e25b7ea
diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex ac8932f122d6..e70a61c6bc63 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -591,6 +591,7 @@ SPECTACULAR_SETTINGS = {"EvaluationTargetEnum": "products.ai_observability.backend.models.evaluations.EvaluationTarget","IntegrationKindEnum": "posthog.models.integration.Integration.IntegrationKind","TicketStatusEnum": "products.conversations.backend.models.constants.Status",+ "EmailChannelKindEnum": "products.conversations.backend.models.team_conversations_email_config.EmailChannelKind",# Shared by Ticket.priority and TicketViewFilters.priority (same choice set)."TicketPriorityEnum": "products.conversations.backend.models.constants.Priority","TicketChannelFilterEnum": "products.conversations.backend.api.ticket_filters.TICKET_CHANNEL_FILTER_CHOICES",diff --git a/products/conversations/backend/api/email_events.py b/products/conversations/backend/api/email_events.pyindex 83589dce7e88..41109348753f 100644--- a/products/conversations/backend/api/email_events.py+++ b/products/conversations/backend/api/email_events.py@@ -18,7 +18,7 @@ from posthog.models.team import Teamfrom posthog.models.user import Userfrom products.conversations.backend.mailgun import validate_webhook_signature-from products.conversations.backend.models import Channel, EmailChannel, EmailMessageMapping, Status+from products.conversations.backend.models import Channel, EmailChannel, EmailChannelKind, EmailMessageMapping, Statusfrom products.conversations.backend.models.ticket import Ticketfrom products.conversations.backend.services.attachments import (sanitize_attachment_filename,@@ -322,6 +322,9 @@ def email_inbound_handler(request: HttpRequest) -> HttpResponse:return HttpResponse("Unknown recipient", status=404)team = config.team+ if config.kind != EmailChannelKind.SUPPORT:+ logger.info("email_inbound_customer_communication_deferred", team_id=team.id, config_id=str(config.id))+ return HttpResponse(status=200)# 3. Check email_enabledsettings_dict = team.conversations_settings or {}diff --git a/products/conversations/backend/api/email_settings.py b/products/conversations/backend/api/email_settings.pyindex f2d661f11f20..7905d960ba61 100644--- a/products/conversations/backend/api/email_settings.py+++ b/products/conversations/backend/api/email_settings.py@@ -8,6 +8,7 @@ from django.core import mailfrom django.db import IntegrityError, transactionimport structlog+from drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import serializersfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Request@@ -15,6 +16,7 @@ from rest_framework.response import Responsefrom rest_framework.views import APIViewfrom posthog.models.instance_setting import get_instance_setting+from posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.rate_limit import EmailSendTestThrottle, EmailVerifyDomainThrottle@@ -30,8 +32,11 @@ from products.conversations.backend.mailgun import (send_mime,verify_domain as mailgun_verify_domain,)-from products.conversations.backend.models import EmailChannel-from products.conversations.backend.models.team_conversations_email_config import MAX_EMAIL_CONFIGS_PER_TEAM+from products.conversations.backend.models import EmailChannel, EmailChannelKind+from products.conversations.backend.models.team_conversations_email_config import (+ MAX_CUSTOMER_COMMUNICATION_CHANNELS_PER_TEAM,+ MAX_EMAIL_CONFIGS_PER_TEAM,+)from products.conversations.backend.permissions import IsConversationsAdminlogger = structlog.get_logger(__name__)@@ -59,6 +64,14 @@ def _get_config_for_team(config_id: uuid.UUID, team: Team) -> EmailChannel | Nonreturn EmailChannel.objects.filter(id=config_id, team=team).first()+def _is_organization_admin(user: User, team: Team) -> bool:+ return OrganizationMembership.objects.filter(+ organization_id=team.organization_id,+ user=user,+ level__gte=OrganizationMembership.Level.ADMIN,+ ).exists()++def _resolve_config_from_request(request: Request) -> tuple[User, Team, EmailChannel] | Response:"""Parse config_id from request body, look up config scoped to team.@@ -83,6 +96,8 @@ def _config_to_dict(config: EmailChannel, inbound_domain: str | None = None) ->forwarding_address = f"team-{config.inbound_token}@{inbound_domain}" if inbound_domain else Nonereturn {"id": config.id,+ "kind": config.kind,+ "owner_id": config.owner_id,"from_email": config.from_email,"from_name": config.from_name,"forwarding_address": forwarding_address,@@ -171,9 +186,29 @@ def _try_reclaim_stranded_domain(team: Team, domain: str) -> dict | None:return dns_records+class EmailChannelKindQuerySerializer(serializers.Serializer):+ kind = serializers.ChoiceField(+ choices=EmailChannelKind.choices,+ default=EmailChannelKind.SUPPORT,+ required=False,+ help_text="Email channel kind to return. Defaults to support channels.",+ )++class EmailConnectSerializer(serializers.Serializer):- from_email = serializers.EmailField()- from_name = serializers.CharField(max_length=255)+ from_email = serializers.EmailField(help_text="Email address that receives forwarded mail and sends replies.")+ from_name = serializers.CharField(max_length=255, help_text="Display name used for outbound email.")+ kind = serializers.ChoiceField(+ choices=EmailChannelKind.choices,+ default=EmailChannelKind.SUPPORT,+ required=False,+ help_text="Whether the address handles support or customer communication.",+ )+ owner_id = serializers.IntegerField(+ required=False,+ allow_null=True,+ help_text="Organization member who owns a customer communication channel. Must be omitted for support.",+ )def validate_from_email(self, value: str) -> str:return value.lower()@@ -184,23 +219,113 @@ class EmailConnectSerializer(serializers.Serializer):raise serializers.ValidationError("Display name cannot be blank.")return value+ def validate(self, attrs: dict) -> dict:+ kind = attrs.get("kind", EmailChannelKind.SUPPORT)+ owner_id = attrs.get("owner_id")+ if kind == EmailChannelKind.CUSTOMER_COMMUNICATION and owner_id is None:+ raise serializers.ValidationError({"owner_id": "Owner is required for customer communication channels."})+ if kind == EmailChannelKind.SUPPORT and owner_id is not None:+ raise serializers.ValidationError({"owner_id": "Support channels cannot have an owner."})+ return attrs+class ConfigIdSerializer(serializers.Serializer):- config_id = serializers.UUIDField()+ config_id = serializers.UUIDField(help_text="Email channel ID.")+++class EmailDnsRecordSerializer(serializers.Serializer):+ record_type = serializers.CharField(required=False, allow_blank=True, help_text="DNS record type.")+ name = serializers.CharField(required=False, allow_blank=True, help_text="DNS record hostname.")+ value = serializers.CharField(required=False, allow_blank=True, help_text="DNS record value.")+ valid = serializers.CharField(required=False, allow_blank=True, help_text="Mailgun verification status.")+++class EmailDnsRecordsSerializer(serializers.Serializer):+ sending_dns_records = EmailDnsRecordSerializer(+ many=True,+ required=False,+ help_text="DNS records required for outbound sending.",+ )+++class EmailChannelConfigSerializer(serializers.Serializer):+ id = serializers.UUIDField(read_only=True, help_text="Email channel ID.")+ kind = serializers.ChoiceField(+ choices=EmailChannelKind.choices,+ read_only=True,+ help_text="Whether the channel handles support or customer communication.",+ )+ owner_id = serializers.IntegerField(+ read_only=True,+ allow_null=True,+ help_text="User who owns a customer communication channel, or null for support.",+ )+ from_email = serializers.EmailField(read_only=True, help_text="Sender and forwarding source email address.")+ from_name = serializers.CharField(read_only=True, help_text="Outbound sender display name.")+ forwarding_address = serializers.EmailField(+ read_only=True,+ allow_null=True,+ help_text="PostHog address to configure as a forwarding destination.",+ )+ domain = serializers.CharField(read_only=True, help_text="Sending domain registered with Mailgun.")+ domain_verified = serializers.BooleanField(read_only=True, help_text="Whether Mailgun verified the domain.")+ dns_records = EmailDnsRecordsSerializer(+ read_only=True,+ allow_null=True,+ help_text="DNS records required to verify the sending domain.",+ )+ is_default = serializers.BooleanField(+ read_only=True,+ help_text="Whether this support channel is the team's fallback sender.",+ )+++class EmailStatusResponseSerializer(serializers.Serializer):+ configs = EmailChannelConfigSerializer(many=True, read_only=True, help_text="Connected email channels.")+++class EmailConnectResponseSerializer(serializers.Serializer):+ ok = serializers.BooleanField(read_only=True, help_text="Whether the channel was connected.")+ config = EmailChannelConfigSerializer(read_only=True, help_text="Connected email channel.")+++class EmailChannelErrorSerializer(serializers.Serializer):+ error = serializers.CharField(read_only=True, help_text="Reason the request failed.")+++class EmailChannelOperationResponseSerializer(serializers.Serializer):+ ok = serializers.BooleanField(read_only=True, help_text="Whether the operation succeeded.")+++class EmailSendTestResponseSerializer(EmailChannelOperationResponseSerializer):+ sent_to = serializers.EmailField(read_only=True, help_text="Address that received the test email.")class EmailStatusView(APIView):- """Return all email configs for the current team."""+ """Return connected email channels for the current team."""permission_classes = [IsAuthenticated]+ @extend_schema(+ parameters=[EmailChannelKindQuerySerializer],+ responses={+ 200: EmailStatusResponseSerializer,+ 400: OpenApiResponse(response=EmailChannelErrorSerializer),+ },+ )def get(self, request: Request, *args, **kwargs) -> Response:result = _get_team_from_request(request)if isinstance(result, Response):return result- _, team = result+ user, team = result- configs = EmailChannel.objects.filter(team=team).order_by("created_at")+ query_serializer = EmailChannelKindQuerySerializer(data=request.query_params)+ 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):+ configs = configs.filter(owner=user)+ configs = configs.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]})@@ -209,6 +334,15 @@ class EmailStatusView(APIView):class EmailConnectView(APIView):permission_classes = [IsAuthenticated, IsConversationsAdmin]+ @extend_schema(+ request=EmailConnectSerializer,+ responses={+ 200: EmailConnectResponseSerializer,+ 400: OpenApiResponse(response=EmailChannelErrorSerializer),+ 409: OpenApiResponse(response=EmailChannelErrorSerializer),+ 502: OpenApiResponse(response=EmailChannelErrorSerializer),+ },+ )def post(self, request: Request, *args, **kwargs) -> Response:result = _get_team_from_request(request)if isinstance(result, Response):@@ -220,8 +354,23 @@ class EmailConnectView(APIView):from_email: str = serializer.validated_data["from_email"]from_name: str = serializer.validated_data["from_name"]- domain = from_email.split("@")[1]+ kind: str = serializer.validated_data["kind"]+ owner: User | None = None+ if kind == EmailChannelKind.CUSTOMER_COMMUNICATION:+ membership = (+ OrganizationMembership.objects.filter(+ organization_id=team.organization_id,+ user_id=serializer.validated_data["owner_id"],+ user__is_active=True,+ )+ .select_related("user")+ .first()+ )+ if membership is None:+ return Response({"error": "Owner must be an active member of this organization."}, status=400)+ owner = membership.user+ domain = from_email.split("@")[1]inbound_domain = get_instance_setting("CONVERSATIONS_EMAIL_INBOUND_DOMAIN")if not inbound_domain:return Response(@@ -233,8 +382,12 @@ class EmailConnectView(APIView):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)- # Check if org already has a config on this domain (reuse Mailgun registration + DNS records)- sibling = EmailChannel.objects.filter(team__organization_id=team.organization_id, domain=domain).first()+ # 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()+ )dns_records: dict = {}if sibling:@@ -271,25 +424,33 @@ class EmailConnectView(APIView):# Lock team row to serialize concurrent connects and enforce the config limitTeam.objects.select_for_update().get(id=team.id)- current_count = EmailChannel.objects.filter(team=team).count()- if current_count >= MAX_EMAIL_CONFIGS_PER_TEAM:+ current_count = EmailChannel.objects.filter(team=team, kind=kind).count()+ max_channels = (+ MAX_EMAIL_CONFIGS_PER_TEAM+ if kind == EmailChannelKind.SUPPORT+ else MAX_CUSTOMER_COMMUNICATION_CHANNELS_PER_TEAM+ )+ if current_count >= max_channels:+ channel_name = "support" if kind == EmailChannelKind.SUPPORT else "customer communication"failure = Response(- {"error": f"Maximum of {MAX_EMAIL_CONFIGS_PER_TEAM} email addresses per team."},+ {"error": f"Maximum of {max_channels} {channel_name} email addresses per team."},status=400,)else:config = EmailChannel.objects.create(team=team,+ kind=kind,+ owner=owner,inbound_token=secrets.token_hex(16),from_email=from_email,from_name=from_name,domain=domain,dns_records=dns_records,domain_verified=sibling.domain_verified if sibling else False,- # First channel becomes the team default so there's always one to send from- is_default=current_count == 0,+ is_default=kind == EmailChannelKind.SUPPORT and current_count == 0,)- _set_email_enabled(team, enabled=True)+ if kind == EmailChannelKind.SUPPORT:+ _set_email_enabled(team, enabled=True)except IntegrityError:failure = Response({"error": "This email address is already connected."}, status=409)@@ -307,6 +468,8 @@ class EmailConnectView(APIView):domain=domain,from_email=from_email,config_id=config.id,+ kind=config.kind,+ owner_id=config.owner_id,user_id=user.id,)@@ -360,12 +523,28 @@ class EmailSendTestView(APIView):permission_classes = [IsAuthenticated]throttle_classes = [EmailSendTestThrottle]+ @extend_schema(+ request=ConfigIdSerializer,+ responses={+ 200: EmailSendTestResponseSerializer,+ 400: OpenApiResponse(response=EmailChannelErrorSerializer),+ 404: OpenApiResponse(response=EmailChannelErrorSerializer),+ 500: OpenApiResponse(response=EmailChannelErrorSerializer),+ 502: OpenApiResponse(response=EmailChannelErrorSerializer),+ },+ )def post(self, request: Request, *args, **kwargs) -> Response:result = _resolve_config_from_request(request)if isinstance(result, Response):return resultuser, team, config = result+ if (+ config.kind == EmailChannelKind.CUSTOMER_COMMUNICATION+ and config.owner_id != user.id+ and not _is_organization_admin(user, team)+ ):+ return Response({"error": "Email config not found"}, status=404)if not config.domain_verified:return Response({"error": "Domain not yet verified. Please verify DNS records first."}, status=400)@@ -418,10 +597,18 @@ class EmailSendTestView(APIView):class EmailSetDefaultView(APIView):- """Make a channel the team's default send-from identity (one default per team)."""+ """Make a support channel the team's default send-from identity."""permission_classes = [IsAuthenticated, IsConversationsAdmin]+ @extend_schema(+ request=ConfigIdSerializer,+ responses={+ 200: EmailChannelOperationResponseSerializer,+ 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):@@ -440,9 +627,15 @@ class EmailSetDefaultView(APIView):config = EmailChannel.objects.filter(id=config_id, team=team).first()if not config:return Response({"error": "Email config not found"}, status=404)-- # Clear the current default first so the partial unique constraint is never violated- EmailChannel.objects.filter(team=team, is_default=True).exclude(id=config.id).update(is_default=False)+ if config.kind != EmailChannelKind.SUPPORT:+ return Response({"error": "Only support email channels can be primary."}, status=400)++ # Clear the current default first so the partial unique constraint is never violated.+ EmailChannel.objects.filter(+ team=team,+ kind=EmailChannelKind.SUPPORT,+ is_default=True,+ ).exclude(id=config.id).update(is_default=False)if not config.is_default:config.is_default = Trueconfig.save(update_fields=["is_default"])@@ -454,6 +647,13 @@ class EmailSetDefaultView(APIView):class EmailDisconnectView(APIView):permission_classes = [IsAuthenticated, IsConversationsAdmin]+ @extend_schema(+ request=ConfigIdSerializer,+ responses={+ 200: EmailChannelOperationResponseSerializer,+ 404: OpenApiResponse(response=EmailChannelErrorSerializer),+ },+ )def post(self, request: Request, *args, **kwargs) -> Response:result = _get_team_from_request(request)if isinstance(result, Response):@@ -479,10 +679,13 @@ class EmailDisconnectView(APIView):was_default = config.is_defaultconfig.delete()- # If the team default was removed, promote another channel (prefer verified, then oldest)- # so the team keeps a channel to send from+ # Keep a support fallback sender after its previous default is removed.if was_default:- replacement = EmailChannel.objects.filter(team=team).order_by("-domain_verified", "created_at").first()+ replacement = (+ EmailChannel.objects.filter(team=team, kind=EmailChannelKind.SUPPORT)+ .order_by("-domain_verified", "created_at")+ .first()+ )if replacement:replacement.is_default = Truereplacement.save(update_fields=["is_default"])@@ -491,8 +694,8 @@ class EmailDisconnectView(APIView):if not EmailChannel.objects.filter(domain=domain_to_delete).exists():should_delete_from_mailgun = True- # Only disable email on team if this was the last config- if not EmailChannel.objects.filter(team=team).exists():+ # The legacy setting controls support email, not customer communication capture.+ if not EmailChannel.objects.filter(team=team, kind=EmailChannelKind.SUPPORT).exists():_set_email_enabled(team, enabled=False)if should_delete_from_mailgun:diff --git a/products/conversations/backend/api/tests/test_email_endpoints.py b/products/conversations/backend/api/tests/test_email_endpoints.pyindex 8f9b54402b13..761053359d4c 100644--- a/products/conversations/backend/api/tests/test_email_endpoints.py+++ b/products/conversations/backend/api/tests/test_email_endpoints.py@@ -14,6 +14,7 @@ from PIL import Imagefrom posthog.models.comment import Commentfrom posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team import Team+from posthog.models.user import Userfrom products.conversations.backend.mailgun import (MailgunDomainConflict,@@ -22,7 +23,7 @@ from products.conversations.backend.mailgun import (MailgunPermanentError,MailgunTransientError,)-from products.conversations.backend.models import EmailChannel, EmailOutboxMessage+from products.conversations.backend.models import EmailChannel, EmailChannelKind, EmailOutboxMessagefrom products.conversations.backend.models.ticket import Ticket@@ -149,6 +150,57 @@ class TestEmailChannelPermissions(BaseTest):)assert response.status_code == 404+ def test_member_lists_only_owned_customer_communication_channels(self) -> None:+ other_owner = User.objects.create(email="[email protected]")+ OrganizationMembership.objects.create(+ organization=self.organization,+ user=other_owner,+ level=OrganizationMembership.Level.MEMBER,+ )+ for owner, token in ((self.user, "owned-token"), (other_owner, "other-token")):+ EmailChannel.objects.create(+ team=self.team,+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ owner=owner,+ inbound_token=token,+ from_email=owner.email,+ from_name="Customer success",+ domain="example.com",+ )++ response = self.client.get(f"/api/conversations/v1/email/status?kind={EmailChannelKind.CUSTOMER_COMMUNICATION}")++ 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.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]")+ 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-token",+ from_email=other_owner.email,+ from_name="Customer success",+ domain="example.com",+ domain_verified=True,+ )++ response = self.client.post(+ "/api/conversations/v1/email/send-test",+ {"config_id": str(channel.id)},+ content_type="application/json",+ )++ assert response.status_code == 404+ mock_send_mime.assert_not_called()+class TestEmailMultiConfig(BaseTest):def setUp(self):@@ -495,6 +547,158 @@ class TestEmailMultiConfig(BaseTest):emails = {c["from_email"] for c in data["configs"]}assert emails == {"[email protected]", "[email protected]"}+ @patch("products.conversations.backend.api.email_settings.mailgun_add_domain", return_value={})+ @patch(+ "products.conversations.backend.api.email_settings.get_instance_setting",+ return_value="mg.posthog.com",+ )+ def test_connect_customer_communication_channel(self, _mock_setting: MagicMock, _mock_mailgun: MagicMock) -> None:+ 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+ config = EmailChannel.objects.get(team=self.team)+ assert config.kind == EmailChannelKind.CUSTOMER_COMMUNICATION+ assert config.owner_id == self.user.id+ assert config.is_default is False+ assert response.json()["config"]["kind"] == EmailChannelKind.CUSTOMER_COMMUNICATION+ assert response.json()["config"]["owner_id"] == self.user.id+ 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_rejects_owner_outside_organization(+ self, _mock_setting: MagicMock, mock_mailgun: MagicMock+ ) -> None:+ response = self.client.post(+ "/api/conversations/v1/email/connect",+ {+ "from_email": "[email protected]",+ "from_name": "Customer success",+ "kind": EmailChannelKind.CUSTOMER_COMMUNICATION,+ "owner_id": 999999,+ },+ content_type="application/json",+ )++ assert response.status_code == 400+ assert response.json()["error"] == "Owner must be an active member of this organization."+ assert not EmailChannel.objects.filter(team=self.team).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",+ return_value="mg.posthog.com",+ )+ def test_customer_channel_reuses_verified_support_domain(+ self, _mock_setting: MagicMock, mock_mailgun: MagicMock+ ) -> None:+ EmailChannel.objects.create(+ team=self.team,+ inbound_token="support-token",+ from_email="[email protected]",+ from_name="Support",+ domain="example.com",+ domain_verified=True,+ dns_records={"sending_dns_records": [{"record_type": "TXT", "value": "verified"}]},+ is_default=True,+ )++ 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+ 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"}]}+ mock_mailgun.assert_not_called()++ @patch(+ "products.conversations.backend.api.email_settings.get_instance_setting",+ return_value="mg.posthog.com",+ )+ def test_status_filters_channels_by_kind(self, _mock_setting: MagicMock) -> None:+ EmailChannel.objects.create(+ team=self.team,+ inbound_token="support-token",+ from_email="[email protected]",+ from_name="Support",+ domain="example.com",+ )+ EmailChannel.objects.create(+ team=self.team,+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ owner=self.user,+ inbound_token="customer-token",+ from_email="[email protected]",+ from_name="Customer success",+ domain="example.com",+ )++ support_response = self.client.get("/api/conversations/v1/email/status")+ customer_response = self.client.get(+ f"/api/conversations/v1/email/status?kind={EmailChannelKind.CUSTOMER_COMMUNICATION}"+ )++ assert [config["from_email"] for config in support_response.json()["configs"]] == ["[email protected]"]+ assert [config["from_email"] for config in customer_response.json()["configs"]] == ["[email protected]"]+ assert customer_response.json()["configs"][0]["owner_id"] == 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_support_channel_limit_does_not_block_customer_channels(+ self, _mock_setting: MagicMock, mock_mailgun: MagicMock+ ) -> None:+ from products.conversations.backend.models.team_conversations_email_config import MAX_EMAIL_CONFIGS_PER_TEAM++ for index in range(MAX_EMAIL_CONFIGS_PER_TEAM):+ EmailChannel.objects.create(+ team=self.team,+ inbound_token=f"support-token-{index}",+ from_email=f"support-{index}@example.com",+ from_name="Support",+ domain="example.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(kind=EmailChannelKind.CUSTOMER_COMMUNICATION).count() == 1+ mock_mailgun.assert_not_called()+@patch("products.conversations.backend.api.email_settings.mailgun_delete_domain")@patch("products.conversations.backend.api.email_settings.mailgun_add_domain", return_value={})@patch(@@ -828,6 +1032,35 @@ class TestEmailInboundMultiConfig(BaseTest):ticket = Ticket.objects.get(team=self.team)assert ticket.email_config_id == config2.id+ @patch("products.conversations.backend.api.email_events.validate_webhook_signature", return_value=True)+ def test_customer_communication_channel_does_not_create_support_ticket(self, _mock_sig: MagicMock) -> None:+ config = EmailChannel.objects.create(+ team=self.team,+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ owner=self.user,+ inbound_token="c0570a111",+ from_email="[email protected]",+ from_name="Customer success",+ domain="example.com",+ domain_verified=True,+ )++ response = self.client.post(+ "/api/conversations/v1/email/inbound",+ {+ "recipient": "[email protected]",+ "from": "[email protected]",+ "Message-Id": "<[email protected]>",+ "subject": "Account question",+ "stripped-text": "Can you help?",+ },+ )++ assert response.status_code == 200+ assert not Ticket.objects.filter(team=self.team).exists()+ assert not Comment.objects.filter(team=self.team).exists()+ assert EmailChannel.objects.get(id=config.id).kind == EmailChannelKind.CUSTOMER_COMMUNICATION+class TestEmailInboundContent(BaseTest):def setUp(self):@@ -1948,9 +2181,18 @@ class TestEmailDefaultChannel(BaseTest):self.organization_membership.save()self.client.force_login(self.user)- def _create_config(self, from_email: str, *, verified: bool = True, is_default: bool = False) -> EmailChannel:+ def _create_config(+ self,+ from_email: str,+ *,+ verified: bool = True,+ is_default: bool = False,+ kind: str = EmailChannelKind.SUPPORT,+ ) -> EmailChannel:return EmailChannel.objects.create(team=self.team,+ kind=kind,+ owner=self.user if kind == EmailChannelKind.CUSTOMER_COMMUNICATION else None,inbound_token=from_email,from_email=from_email,from_name="Support",@@ -1995,10 +2237,30 @@ class TestEmailDefaultChannel(BaseTest):assert first.is_default is Falseassert second.is_default is True+ def test_customer_communication_channel_cannot_become_default(self) -> None:+ customer_channel = self._create_config(+ "[email protected]",+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ )++ response = self.client.post(+ "/api/conversations/v1/email/set-default",+ {"config_id": str(customer_channel.id)},+ content_type="application/json",+ )++ assert response.status_code == 400+ customer_channel.refresh_from_db()+ assert customer_channel.is_default is False+@patch("products.conversations.backend.api.email_settings.mailgun_delete_domain")- def test_disconnecting_default_promotes_a_replacement(self, _mock_delete: MagicMock):+ def test_disconnecting_default_promotes_a_support_replacement(self, _mock_delete: MagicMock) -> None:default = self._create_config("[email protected]", is_default=True)other = self._create_config("[email protected]")+ customer_channel = self._create_config(+ "[email protected]",+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ )response = self.client.post("/api/conversations/v1/email/disconnect",@@ -2008,4 +2270,26 @@ class TestEmailDefaultChannel(BaseTest):assert response.status_code == 200other.refresh_from_db()+ customer_channel.refresh_from_db()assert other.is_default is True+ assert customer_channel.is_default is False++ @patch("products.conversations.backend.api.email_settings.mailgun_delete_domain")+ def test_disconnecting_last_support_channel_disables_support_email(self, _mock_delete: MagicMock) -> None:+ support_channel = self._create_config("[email protected]", is_default=True)+ self._create_config(+ "[email protected]",+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ )+ self.team.conversations_settings = {"email_enabled": True}+ self.team.save(update_fields=["conversations_settings"])++ response = self.client.post(+ "/api/conversations/v1/email/disconnect",+ {"config_id": str(support_channel.id)},+ content_type="application/json",+ )++ assert response.status_code == 200+ self.team.refresh_from_db()+ assert (self.team.conversations_settings or {}).get("email_enabled") is Falsediff --git a/products/conversations/backend/api/tests/test_tickets.py b/products/conversations/backend/api/tests/test_tickets.pyindex c8d9aa264ba9..2cf80f6cfdc6 100644--- a/products/conversations/backend/api/tests/test_tickets.py+++ b/products/conversations/backend/api/tests/test_tickets.py@@ -33,7 +33,7 @@ from posthog.test.persons import create_personfrom products.conversations.backend.api.ticket_filters import query_params_to_view_filtersfrom products.conversations.backend.api.tickets import TicketReplyRequestSerializer-from products.conversations.backend.models import Ticket, TicketAssignment, TicketView+from products.conversations.backend.models import EmailChannel, EmailChannelKind, Ticket, TicketAssignment, TicketViewfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Priority, Statusfrom products.conversations.backend.person_lookup import PERSON_EMAIL_LOOKUP_QUERY, _get_persons_by_emailfrom products.conversations.backend.reply_dedupe import REPLY_IN_PROGRESS_ERROR_TYPE, ReplyFingerprint, reserve@@ -1809,8 +1809,6 @@ class TestComposeTicketAPI(APIBaseTest):self.team.conversations_enabled = Trueself.team.conversations_settings = {"email_enabled": True}self.team.save()- from products.conversations.backend.models import EmailChannel-self.email_config = EmailChannel.objects.create(team=self.team,from_email="[email protected]",@@ -1918,6 +1916,29 @@ class TestComposeTicketAPI(APIBaseTest):if expected_detail:assert expected_detail in response.json()["detail"]+ def test_compose_rejects_customer_communication_channel(self, mock_on_commit) -> None:+ customer_channel = EmailChannel.objects.create(+ team=self.team,+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ owner=self.user,+ from_email="[email protected]",+ from_name="Customer success",+ domain="example.com",+ domain_verified=True,+ inbound_token="customer-channel-compose",+ )++ response = self._compose(+ {+ "recipient_email": "[email protected]",+ "email_config_id": str(customer_channel.id),+ "message": "Hello!",+ }+ )++ assert response.status_code == status.HTTP_400_BAD_REQUEST+ assert not Ticket.objects.filter(team=self.team).exists()+def test_composed_ticket_is_not_born_verified(self, mock_on_commit):# The team typed the recipient address; the recipient never proved they control it,# so an outbound ticket must start with unknown identity (None) — never verified.diff --git a/products/conversations/backend/api/tests/test_zendesk_import.py b/products/conversations/backend/api/tests/test_zendesk_import.pyindex 903da4eea545..0de8020d6a60 100644--- a/products/conversations/backend/api/tests/test_zendesk_import.py+++ b/products/conversations/backend/api/tests/test_zendesk_import.py@@ -7,7 +7,7 @@ from posthog.models.organization import Organization, OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.models.utils import generate_random_token_secret-from products.conversations.backend.models import ZendeskImportJob+from products.conversations.backend.models import EmailChannel, EmailChannelKind, ZendeskImportJobclass TestZendeskImportAPI(APIBaseTest):@@ -72,6 +72,31 @@ class TestZendeskImportAPI(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_customer_communication_channel_cannot_be_import_default(self) -> None:+ customer_channel = EmailChannel.objects.create(+ team=self.team,+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ owner=self.user,+ inbound_token="customer-zendesk-token",+ from_email="[email protected]",+ from_name="Customer success",+ domain="example.com",+ )++ response = self.client.post(+ f"/api/projects/{self.team.id}/conversations/zendesk_imports/",+ {+ "subdomain": "acme",+ "email_address": "[email protected]",+ "api_token": generate_random_token_secret(),+ "default_email_channel_id": str(customer_channel.id),+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertFalse(ZendeskImportJob.objects.unscoped().filter(team_id=self.team.id).exists())+def test_non_admin_member_cannot_start_or_poll(self):# A plain member of the routed team must not be able to start an import or read status —# the endpoint requires org-admin, not just team membership.diff --git a/products/conversations/backend/api/tickets.py b/products/conversations/backend/api/tickets.pyindex adc659059a15..883a12d32810 100644--- a/products/conversations/backend/api/tickets.py+++ b/products/conversations/backend/api/tickets.py@@ -61,7 +61,7 @@ from products.conversations.backend.events import (capture_ticket_status_changed,)from products.conversations.backend.metrics import TICKET_SEARCH_DURATION_SECONDS-from products.conversations.backend.models import EmailChannel, Ticket, TicketAssignment, TicketView+from products.conversations.backend.models import EmailChannel, EmailChannelKind, Ticket, TicketAssignment, TicketViewfrom products.conversations.backend.models.constants import Channel, ChannelDetail, Statusfrom products.conversations.backend.person_lookup import _get_persons_by_email@@ -1474,6 +1474,7 @@ class TicketViewSet(TaggedItemViewSetMixin, TeamAndOrgViewSetMixin, AccessControemail_config = EmailChannel.objects.filter(id=data["email_config_id"],team=team,+ kind=EmailChannelKind.SUPPORT,domain_verified=True,).first()if not email_config:diff --git a/products/conversations/backend/api/zendesk_import.py b/products/conversations/backend/api/zendesk_import.pyindex 5195e0f30f32..752993471e65 100644--- a/products/conversations/backend/api/zendesk_import.py+++ b/products/conversations/backend/api/zendesk_import.py@@ -19,7 +19,7 @@ from rest_framework.response import Responsefrom posthog.api.routing import TeamAndOrgViewSetMixin-from products.conversations.backend.models import EmailChannel, ZendeskImportJob+from products.conversations.backend.models import EmailChannel, EmailChannelKind, ZendeskImportJobfrom products.conversations.backend.permissions import IsConversationsAdminfrom products.conversations.backend.temporal.zendesk_import.client import (ZendeskCredentials,@@ -160,7 +160,11 @@ class ZendeskImportViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):default_email_channel_id = data.get("default_email_channel_id")if (default_email_channel_id is not None- and not EmailChannel.objects.filter(team_id=team_id, id=default_email_channel_id).exists()+ and not EmailChannel.objects.filter(+ team_id=team_id,+ id=default_email_channel_id,+ kind=EmailChannelKind.SUPPORT,+ ).exists()):return Response({"detail": "The selected default email channel does not belong to this team"},diff --git a/products/conversations/backend/migrations/0057_email_channel_kind_and_owner.py b/products/conversations/backend/migrations/0057_email_channel_kind_and_owner.pynew file mode 100644index 000000000000..4a14ac8cbeca--- /dev/null+++ b/products/conversations/backend/migrations/0057_email_channel_kind_and_owner.py@@ -0,0 +1,38 @@+# Generated by Django 5.2.17 on 2026-08-10 13:36++import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0056_backfill_signing_secret"),+ ("posthog", "1296_backfill_cimd_verification_token_url"),+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ]++ operations = [+ migrations.AddField(+ model_name="emailchannel",+ name="kind",+ field=models.CharField(+ choices=[("support", "Support"), ("customer_communication", "Customer communication")],+ db_default="support",+ default="support",+ max_length=32,+ ),+ ),+ migrations.AddField(+ model_name="emailchannel",+ name="owner",+ field=models.ForeignKey(+ blank=True,+ db_constraint=False,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="owned_conversations_email_channels",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ]diff --git a/products/conversations/backend/migrations/0058_add_email_channel_kind_constraint.py b/products/conversations/backend/migrations/0058_add_email_channel_kind_constraint.pynew file mode 100644index 000000000000..c81244c1e445--- /dev/null+++ b/products/conversations/backend/migrations/0058_add_email_channel_kind_constraint.py@@ -0,0 +1,29 @@+from django.db import migrations, models++from posthog.migration_helpers import AddConstraintNotValid+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0057_email_channel_kind_and_owner"),+ ]++ operations = [+ AddConstraintNotValid(+ model_name="emailchannel",+ constraint=models.CheckConstraint(+ condition=models.Q(kind="support") | models.Q(is_default=False),+ name="email_channel_customer_not_default",+ ),+ ),+ AddConstraintNotValid(+ model_name="emailchannel",+ constraint=models.CheckConstraint(+ condition=(+ models.Q(kind="support", owner__isnull=True)+ | models.Q(kind="customer_communication", owner__isnull=False)+ ),+ name="email_channel_kind_owner",+ ),+ ),+ ]diff --git a/products/conversations/backend/migrations/0059_validate_email_channel_kind_constraint.py b/products/conversations/backend/migrations/0059_validate_email_channel_kind_constraint.pynew file mode 100644index 000000000000..67fdd8e20ee7--- /dev/null+++ b/products/conversations/backend/migrations/0059_validate_email_channel_kind_constraint.py@@ -0,0 +1,14 @@+from django.db import migrations++from posthog.migration_helpers import ValidateConstraint+++class Migration(migrations.Migration):+ dependencies = [+ ("conversations", "0058_add_email_channel_kind_constraint"),+ ]++ operations = [+ ValidateConstraint(model_name="emailchannel", name="email_channel_customer_not_default"),+ ValidateConstraint(model_name="emailchannel", name="email_channel_kind_owner"),+ ]diff --git a/products/conversations/backend/migrations/max_migration.txt b/products/conversations/backend/migrations/max_migration.txtindex c0786bd744c5..2260130ccb67 100644--- a/products/conversations/backend/migrations/max_migration.txt+++ b/products/conversations/backend/migrations/max_migration.txt@@ -1 +1 @@-0056_backfill_signing_secret+0059_validate_email_channel_kind_constraintdiff --git a/products/conversations/backend/models/__init__.py b/products/conversations/backend/models/__init__.pyindex 1e46a62cc476..449c8d7323c8 100644--- a/products/conversations/backend/models/__init__.py+++ b/products/conversations/backend/models/__init__.py@@ -5,7 +5,7 @@ from .email_outbox_message import EmailOutboxMessagefrom .github_comment_mapping import GithubCommentMappingfrom .restore_token import ConversationRestoreTokenfrom .signing_secret import SigningSecret-from .team_conversations_email_config import EmailChannel+from .team_conversations_email_config import EmailChannel, EmailChannelKindfrom .team_conversations_slack_config import TeamConversationsSlackConfigfrom .team_conversations_teams_channel_sync import TeamConversationsTeamsChannelSyncfrom .team_conversations_teams_config import TeamConversationsTeamsConfig@@ -19,6 +19,7 @@ __all__ = ["ChannelDetail","ConversationRestoreToken","EmailChannel",+ "EmailChannelKind","EmailMessageMapping","EmailOutboxMessage","GithubCommentMapping",diff --git a/products/conversations/backend/models/team_conversations_email_config.py b/products/conversations/backend/models/team_conversations_email_config.pyindex bf8293a20957..38357fc94fa3 100644--- a/products/conversations/backend/models/team_conversations_email_config.py+++ b/products/conversations/backend/models/team_conversations_email_config.py@@ -4,35 +4,44 @@ from posthog.models.team import Teamfrom posthog.models.utils import UUIDModelMAX_EMAIL_CONFIGS_PER_TEAM = 10+MAX_CUSTOMER_COMMUNICATION_CHANNELS_PER_TEAM = 100-class EmailChannel(UUIDModel):- """Per-team email channel configuration (many-per-team).+class EmailChannelKind(models.TextChoices):+ SUPPORT = "support", "Support"+ CUSTOMER_COMMUNICATION = "customer_communication", "Customer communication"- A team can have multiple email channels (e.g. support@, billing@).- Each channel has its own inbound_token for routing and its own sender identity.- The old TeamConversationsEmailConfig (one-per-team, team as PK) still exists- in the DB and will be removed in a follow-up PR.- """+class EmailChannel(UUIDModel):+ """An inbound forwarding address and outbound sender identity for a team."""team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="email_channels")+ kind = models.CharField(+ max_length=32,+ choices=EmailChannelKind.choices,+ default=EmailChannelKind.SUPPORT,+ db_default=EmailChannelKind.SUPPORT,+ )+ owner = models.ForeignKey(+ "posthog.User",+ on_delete=models.CASCADE,+ null=True,+ blank=True,+ db_constraint=False,+ related_name="owned_conversations_email_channels",+ )- # Inbound routing — unique token in the receiving address- # Generated via secrets.token_hex(16) → 32 hex chars (128 bits)+ # The random token keeps the team id out of the public forwarding address and supports rotation.inbound_token = models.CharField(max_length=64, unique=True, db_index=True)- # Sender identityfrom_email = models.EmailField()from_name = models.CharField(max_length=255)- # Domain verification (for outbound SPF/DKIM)domain = models.CharField(max_length=255)domain_verified = models.BooleanField(default=False)dns_records = models.JSONField(default=dict, blank=True)- # The team's primary channel — used as the send-from identity when a channel isn't chosen- # explicitly (e.g. tickets opened from the widget). At most one per team (partial constraint below).+ # Only support channels can be the fallback sender for tickets without an explicit channel.is_default = models.BooleanField(default=False)created_at = models.DateTimeField(auto_now_add=True)@@ -55,4 +64,15 @@ class EmailChannel(UUIDModel):condition=models.Q(is_default=True),name="unique_default_email_channel_per_team",),+ models.CheckConstraint(+ condition=models.Q(kind=EmailChannelKind.SUPPORT) | models.Q(is_default=False),+ name="email_channel_customer_not_default",+ ),+ models.CheckConstraint(+ condition=(+ models.Q(kind=EmailChannelKind.SUPPORT, owner__isnull=True)+ | models.Q(kind=EmailChannelKind.CUSTOMER_COMMUNICATION, owner__isnull=False)+ ),+ name="email_channel_kind_owner",+ ),]diff --git a/products/conversations/backend/temporal/zendesk_import/activities.py b/products/conversations/backend/temporal/zendesk_import/activities.pyindex 4b00c2d21b89..f4d9bfddfd7b 100644--- a/products/conversations/backend/temporal/zendesk_import/activities.py+++ b/products/conversations/backend/temporal/zendesk_import/activities.py@@ -28,7 +28,7 @@ with workflow.unsafe.imports_passed_through():from posthog.sync import database_sync_to_asyncfrom posthog.temporal.common.heartbeat import Heartbeater- from products.conversations.backend.models import EmailChannel, Ticket, ZendeskImportJob+ from products.conversations.backend.models import EmailChannel, EmailChannelKind, Ticket, ZendeskImportJobfrom products.conversations.backend.models.constants import Statusfrom products.conversations.backend.services.attachments import (CONVERSATIONS_MAX_IMAGE_BYTES,@@ -208,7 +208,7 @@ def _import_ticket_batch_sync(input: ImportBatchInput) -> ImportBatchOutput:# customer originally emailed) resolves to the matching EmailChannel. Unmatched/absent# recipients fall back to the caller-selected default channel, if any. Bounded to# MAX_EMAIL_CONFIGS_PER_TEAM rows, so a single query up front is cheap.- email_channels = list(EmailChannel.objects.filter(team_id=team.id))+ email_channels = list(EmailChannel.objects.filter(team_id=team.id, kind=EmailChannelKind.SUPPORT))email_channels_by_addr = {(c.from_email or "").strip().lower(): c for c in email_channels}default_email_channel = Noneif input.default_email_channel_id:diff --git a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.pyindex d62765839372..241ec2eae0b6 100644--- a/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py+++ b/products/conversations/backend/temporal/zendesk_import/tests/test_activities.py@@ -10,7 +10,7 @@ from parameterized import parameterizedfrom posthog.models import Tagfrom posthog.models.comment import Comment-from products.conversations.backend.models import EmailChannel, Ticket, ZendeskImportJob+from products.conversations.backend.models import EmailChannel, EmailChannelKind, Ticket, ZendeskImportJobfrom products.conversations.backend.models.constants import Channel, Priority, Statusfrom products.conversations.backend.temporal.zendesk_import.activities import (ImportBatchInput,@@ -229,9 +229,17 @@ class TestZendeskImportBatchActivity(BaseTest):ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=205)self.assertEqual(ticket.anonymous_traits, {"name": "Ada Lovelace", "email": "[email protected]"})- def _make_channel(self, from_email: str, token: str) -> EmailChannel:+ def _make_channel(+ self,+ from_email: str,+ token: str,+ *,+ kind: str = EmailChannelKind.SUPPORT,+ ) -> EmailChannel:return EmailChannel.objects.create(team=self.team,+ kind=kind,+ owner=self.user if kind == EmailChannelKind.CUSTOMER_COMMUNICATION else None,inbound_token=token,from_email=from_email,from_name="Support",@@ -269,6 +277,23 @@ class TestZendeskImportBatchActivity(BaseTest):expected_id = {"matched": matched.id, "default": default.id, None: None}[expected]self.assertEqual(ticket.email_config_id, expected_id)+ def test_customer_communication_channel_is_not_used_for_zendesk_ticket(self) -> None:+ self._make_channel(+ "[email protected]",+ "tok-customer",+ kind=EmailChannelKind.CUSTOMER_COMMUNICATION,+ )++ self._run_batch(+ [211],+ tickets=[_zd_ticket(211, 10, recipient="[email protected]")],+ users={10: _zd_user(10, "[email protected]", name="Ada")},+ comments_by_ticket={211: []},+ )++ ticket = Ticket.objects.get(team=self.team, zendesk_ticket_id=211)+ self.assertIsNone(ticket.email_config_id)+@parameterized.expand([# null channel (first import ran without a default) → adopt this run's default.