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(workflows): default email sender for new broadcasts and workflow emails (#114682)

Daniel Marchuk469da5334679
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index f559035abb91..495f7dee5948 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -1735,6 +1735,11 @@ export interface TeamWorkflowsConfigApi {
* @nullable
*/
workflow_task_team_rate_limit_per_day?: number | null
+ /**
+ * ID of the verified email integration that new broadcasts and workflow email steps use as their sender. Null means no default. Set automatically when the project's first email sender is verified, and cleared when that integration is deleted.
+ * @nullable
+ */
+ default_email_integration_id?: number | null
}
export interface TeamFeatureFlagPolicyConfigApi {
diff --git a/frontend/src/lib/integrations/IntegrationEmailDomainView.tsx b/frontend/src/lib/integrations/IntegrationEmailDomainView.tsx
index f4fef5bc1777..4daceba308e7 100644
--- a/frontend/src/lib/integrations/IntegrationEmailDomainView.tsx
+++ b/frontend/src/lib/integrations/IntegrationEmailDomainView.tsx
@@ -1,9 +1,12 @@
-import { useActions } from 'kea'
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
import { useState } from 'react'
import { IconCollapse, IconExpand, IconGear, IconLetter, IconTrash } from '@posthog/icons'
import { LemonButton, LemonTag, Tooltip } from '@posthog/lemon-ui'
+import { teamLogic } from 'scenes/teamLogic'
+
import { EmailIntegrationDomainGroupedType, IntegrationType } from '~/types'
import { ChannelType } from 'products/workflows/frontend/Channels/MessageChannels'
@@ -29,6 +32,21 @@ export function IntegrationEmailDomainView({
integration: EmailIntegrationDomainGroupedType
}): JSX.Element {
const { openSetupModal, deleteIntegration } = useActions(integrationsLogic)
+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)
+ const { updateCurrentTeam } = useActions(teamLogic)
+ const defaultSenderId = currentTeam?.workflows_config?.default_email_integration_id ?? null
+
+ const makeDefault = (integrationId: number): void => {
+ updateCurrentTeam({
+ workflows_config: {
+ capture_workflows_engagement_events:
+ currentTeam?.workflows_config?.capture_workflows_engagement_events ?? false,
+ default_email_integration_id: integrationId,
+ },
+ })
+ // pinned: analytics event name
+ posthog.capture('workflows default email sender set', { had_default: defaultSenderId !== null })
+ }
const { domain, integrations } = integration
const verified = integrations.every(isVerified)
const verificationRequired = integrations.some(isVerificationRequired)
@@ -50,6 +68,9 @@ export function IntegrationEmailDomainView({
<span className="text-xs text-secondary">
{integrations.length} {integrations.length === 1 ? 'sender' : 'senders'}
</span>
+ {integrations.some((sender) => sender.id === defaultSenderId) && (
+ <LemonTag type="primary">Default sender</LemonTag>
+ )}
{verificationRequired && (
<Tooltip
title={
@@ -78,6 +99,23 @@ export function IntegrationEmailDomainView({
<span className="flex-1">
{integration.config.name} &lt;{integration.config.email}&gt;
</span>
+ {integration.id === defaultSenderId ? (
+ <Tooltip title="New broadcasts and workflow emails start with this sender">
+ <LemonTag type="primary" data-attr="email-sender-default-tag">
+ Default
+ </LemonTag>
+ </Tooltip>
+ ) : isVerified(integration) ? (
+ <LemonButton
+ type="secondary"
+ size="small"
+ onClick={() => makeDefault(integration.id)}
+ disabledReason={currentTeamLoading ? 'Saving…' : undefined}
+ data-attr="email-sender-make-default"
+ >
+ Make default
+ </LemonButton>
+ ) : null}
<LemonButton
type="primary"
size="small"
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index e10437959cf0..007bd17e39e2 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -944,6 +944,7 @@ export interface WorkflowsConfig {
// Null uses the product default.
workflow_task_rate_limit_per_day?: number | null
workflow_task_team_rate_limit_per_day?: number | null
+ default_email_integration_id?: number | null
}
export interface FeatureFlagPolicyConfig {
diff --git a/posthog/api/team.py b/posthog/api/team.py
index cc845890ec08..592fcdc50e55 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -70,6 +70,7 @@ from posthog.models.event_ingestion_restriction_config import (
)
from posthog.models.filters.utils import validate_group_type_index
from posthog.models.group_type_mapping import cached_group_types_for_team
+from posthog.models.integration.model import Integration
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.product_intent.product_intent import (
ProductIntentSerializer,
@@ -994,6 +995,16 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr
),
)
+ default_email_integration_id = serializers.IntegerField(
+ required=False,
+ allow_null=True,
+ help_text=(
+ "ID of the verified email integration that new broadcasts and workflow email steps use as "
+ "their sender. Null means no default. Set automatically when the project's first email "
+ "sender is verified, and cleared when that integration is deleted."
+ ),
+ )
+
class Meta:
model = TeamWorkflowsConfig
fields = [
@@ -1001,6 +1012,7 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr
"email_tracking_consent_mode",
"workflow_task_rate_limit_per_day",
"workflow_task_team_rate_limit_per_day",
+ "default_email_integration_id",
]
def _enforce_self_serve_ceiling(self, field: str, value: int | None, ceiling: int) -> int | None:
@@ -1031,6 +1043,20 @@ class TeamWorkflowsConfigSerializer(serializers.ModelSerializer, UserAccessContr
"workflow_task_team_rate_limit_per_day", value, MAX_SELF_SERVE_WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY
)
+ def validate_default_email_integration_id(self, value: int | None) -> int | None:
+ if self.parent or value is None:
+ return value
+ sender = (
+ Integration.objects.filter(team_id=self.instance.team_id, kind="email", id=value).only("config").first()
+ if self.instance is not None
+ else None
+ )
+ if sender is None:
+ raise serializers.ValidationError("Choose an email sender from this project.")
+ if not sender.config.get("verified"):
+ raise serializers.ValidationError("Verify this sender's domain before making it the default.")
+ return value
+
def validate_team_workflows_config(team: Team | None, value: dict[str, Any] | None) -> dict[str, Any] | None:
if value is None:
diff --git a/posthog/models/integration/email.py b/posthog/models/integration/email.py
index 269f0df8b7f3..89105deedf23 100644
--- a/posthog/models/integration/email.py
+++ b/posthog/models/integration/email.py
@@ -165,9 +165,27 @@ class EmailIntegration:
self.integration.team_id, [integration.id for integration in all_integrations_for_domain]
)
+ from products.workflows.backend.facade.api import (
+ set_default_email_sender_if_unset, # noqa: PLC0415 — keeps the workflows facade off the model import path
+ )
+
+ set_default_email_sender_if_unset(self.integration.team_id, self.integration.id)
+
return verification_result
+@receiver(models.signals.post_delete, sender=model.Integration)
+def clear_default_email_sender_on_integration_delete(sender: Any, instance: model.Integration, **kwargs: Any) -> None:
+ if instance.kind != "email":
+ return
+
+ from products.workflows.backend.facade.api import (
+ clear_default_email_sender, # noqa: PLC0415 — keeps the workflows facade off the model import path
+ )
+
+ clear_default_email_sender(instance.team_id, instance.id)
+
+
@receiver(models.signals.post_delete, sender=model.Integration)
def cleanup_ses_identity_on_integration_delete(sender: Any, instance: model.Integration, **kwargs: Any) -> None:
# A post_delete signal (rather than viewset perform_destroy) so SES identities are
diff --git a/posthog/models/test/integration/test_email.py b/posthog/models/test/integration/test_email.py
index c92d9eb3a0e9..5e5412a0490f 100644
--- a/posthog/models/test/integration/test_email.py
+++ b/posthog/models/test/integration/test_email.py
@@ -12,6 +12,8 @@ from posthog.models.integration import EmailIntegration, Integration
from posthog.models.organization import Organization
from posthog.models.team.team import Team
+from products.workflows.backend.facade.team_extension import TeamWorkflowsConfig
+
class TestEmailIntegrationDomainValidation(BaseTest):
@patch("products.workflows.backend.facade.api.create_ses_email_domain")
@@ -172,3 +174,35 @@ class TestEmailIntegrationSESCleanupOnDelete(BaseTest):
team.delete()
mock_delete_identity.assert_not_called()
+
+
+class TestEmailIntegrationDefaultSender(BaseTest):
+ def _create_sender(self, email: str) -> Integration:
+ return Integration.objects.create(
+ team=self.team,
+ kind="email",
+ integration_id=email,
+ config={"email": email, "domain": email.split("@")[1], "provider": "maildev", "verified": False},
+ )
+
+ def _default_sender_id(self) -> int | None:
+ return TeamWorkflowsConfig.objects.get(team=self.team).default_email_integration_id
+
+ @patch("posthog.models.integration.email.reload_integrations_on_workers")
+ def test_first_verified_sender_becomes_the_default_and_later_ones_do_not_replace_it(self, _reload):
+ first = self._create_sender("[email protected]")
+ second = self._create_sender("[email protected]")
+
+ EmailIntegration(first).verify()
+ EmailIntegration(second).verify()
+
+ assert self._default_sender_id() == first.id
+
+ @patch("posthog.models.integration.email.reload_integrations_on_workers")
+ def test_deleting_the_default_sender_clears_it(self, _reload):
+ sender = self._create_sender("[email protected]")
+ EmailIntegration(sender).verify()
+
+ sender.delete()
+
+ assert self._default_sender_id() is None
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 8d371caaec67..3e40377cf0c3 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -64,6 +64,7 @@ post_delete:posthog.models.file_system.file_system_mixin.FileSystemSyncMixin.__i
post_delete:posthog.models.file_system.file_system_view_log._drop_view_logs_when_file_deleted
post_delete:posthog.models.global_rate_limit_threshold_config.update_redis_thresholds_on_delete
post_delete:posthog.models.integration.email.cleanup_ses_identity_on_integration_delete
+post_delete:posthog.models.integration.email.clear_default_email_sender_on_integration_delete
post_delete:posthog.models.organization.clean_up_alert_subscriptions_on_membership_removal
post_delete:posthog.models.organization.clean_up_event_streams_on_membership_removal
post_delete:posthog.models.organization.pause_loops_on_membership_removal
diff --git a/products/workflows/backend/facade/api.py b/products/workflows/backend/facade/api.py
index 03bf86ead106..f0553f86f56f 100644
--- a/products/workflows/backend/facade/api.py
+++ b/products/workflows/backend/facade/api.py
@@ -24,6 +24,10 @@ from products.workflows.backend.facade.contracts import (
)
from products.workflows.backend.models import HogFlow, TeamWorkflowsConfig
from products.workflows.backend.services.batch_jobs import create_batch_job
+from products.workflows.backend.services.default_email_sender import (
+ clear_default_email_sender,
+ set_default_email_sender_if_unset,
+)
from products.workflows.backend.services.email_sending_controls import (
ensure_workflows_config,
get_email_sending_state,
@@ -48,6 +52,7 @@ __all__ = [
"WorkflowArchived",
"WorkflowNotFound",
"MIN_EMAIL_SENDING_TIER",
+ "clear_default_email_sender",
"compute_next_occurrences",
"create_batch_job",
"ensure_workflows_config",
@@ -56,6 +61,7 @@ __all__ = [
"get_email_sending_tier_limits",
"get_hog_flows_referencing_template_input_keys",
"max_email_sending_tier",
+ "set_default_email_sender_if_unset",
"set_email_sending_tier",
"suspend_email_sending",
"unsuspend_email_sending",
diff --git a/products/workflows/backend/migrations/0032_teamworkflowsconfig_default_email_integration_id.py b/products/workflows/backend/migrations/0032_teamworkflowsconfig_default_email_integration_id.py
new file mode 100644
index 000000000000..7608a567139b
--- /dev/null
+++ b/products/workflows/backend/migrations/0032_teamworkflowsconfig_default_email_integration_id.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.18 on 2026-10-09 14:56
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("workflows", "0031_team_workflows_config_frequency_cap"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="teamworkflowsconfig",
+ name="default_email_integration_id",
+ field=models.BigIntegerField(blank=True, null=True),
+ ),
+ ]
diff --git a/products/workflows/backend/migrations/max_migration.txt b/products/workflows/backend/migrations/max_migration.txt
index 6e4cea6c9acd..1c4435ec8d69 100644
--- a/products/workflows/backend/migrations/max_migration.txt
+++ b/products/workflows/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0031_team_workflows_config_frequency_cap
+0032_teamworkflowsconfig_default_email_integration_id
diff --git a/products/workflows/backend/models/team_workflows_config.py b/products/workflows/backend/models/team_workflows_config.py
index 682634b89f57..a3ae9ce1fc1b 100644
--- a/products/workflows/backend/models/team_workflows_config.py
+++ b/products/workflows/backend/models/team_workflows_config.py
@@ -50,6 +50,11 @@ class TeamWorkflowsConfig(models.Model):
# can be held at a tier that its sending history would not give it.
email_sending_tier_pinned = models.BooleanField(default=False, db_default=False)
+ # The email sender new broadcasts and workflow email steps start with. A plain id rather than a
+ # foreign key: the editors ignore an id that no longer points at a verified sender, and the
+ # integration delete signal clears it.
+ default_email_integration_id = models.BigIntegerField(null=True, blank=True)
+
# Overrides for AI tasks created by workflows. Null keeps the product defaults;
# zero pauses new task creation at that scope.
workflow_task_rate_limit_per_day = models.IntegerField(null=True, blank=True, validators=[MinValueValidator(0)])
diff --git a/products/workflows/backend/services/default_email_sender.py b/products/workflows/backend/services/default_email_sender.py
new file mode 100644
index 000000000000..81166f7e0186
--- /dev/null
+++ b/products/workflows/backend/services/default_email_sender.py
@@ -0,0 +1,30 @@
+"""The project's default email sender, which new broadcasts and workflow email steps start with."""
+
+from posthog.models.team import Team
+
+from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
+from products.workflows.backend.services.email_sending_controls import ensure_workflows_config
+
+
+def _forget_memoized_config() -> None:
+ # Team.workflows_config is memoized for the whole process, so a write that bypasses the
+ # memoized row would keep serving the old sender to this team's next request.
+ Team.workflows_config.fget.cache_clear()
+
+
+def set_default_email_sender_if_unset(team_id: int, integration_id: int) -> bool:
+ ensure_workflows_config(team_id)
+ updated = TeamWorkflowsConfig.objects.filter(team_id=team_id, default_email_integration_id__isnull=True).update(
+ default_email_integration_id=integration_id
+ )
+ if updated:
+ _forget_memoized_config()
+ return updated > 0
+
+
+def clear_default_email_sender(team_id: int, integration_id: int) -> None:
+ cleared = TeamWorkflowsConfig.objects.filter(team_id=team_id, default_email_integration_id=integration_id).update(
+ default_email_integration_id=None
+ )
+ if cleared:
+ _forget_memoized_config()
diff --git a/products/workflows/backend/test/test_team_workflows_config.py b/products/workflows/backend/test/test_team_workflows_config.py
index 7ac76d14143b..22b8034238ff 100644
--- a/products/workflows/backend/test/test_team_workflows_config.py
+++ b/products/workflows/backend/test/test_team_workflows_config.py
@@ -3,9 +3,11 @@ from posthog.test.base import APIBaseTest
from django.contrib.admin import AdminSite
from django.test import RequestFactory, SimpleTestCase
+from parameterized import parameterized
from rest_framework import status
-from posthog.models import OrganizationMembership
+from posthog.models import OrganizationMembership, Team
+from posthog.models.integration import Integration
from products.workflows.backend.admin.team_workflows_config_admin import TeamWorkflowsConfigAdmin
from products.workflows.backend.models.team_workflows_config import TeamWorkflowsConfig
@@ -47,6 +49,7 @@ class TestTeamWorkflowsConfig(APIBaseTest):
"email_tracking_consent_mode": "off",
"workflow_task_rate_limit_per_day": None,
"workflow_task_team_rate_limit_per_day": None,
+ "default_email_integration_id": None,
}
def test_patch_enables_capture(self) -> None:
@@ -108,4 +111,40 @@ class TestTeamWorkflowsConfig(APIBaseTest):
"email_tracking_consent_mode": "off",
"workflow_task_rate_limit_per_day": None,
"workflow_task_team_rate_limit_per_day": None,
+ "default_email_integration_id": None,
}
+
+ @parameterized.expand(
+ [
+ ("unverified_sender", "email", False, False),
+ ("other_projects_sender", "email", True, True),
+ ("not_an_email_sender", "slack", True, False),
+ ]
+ )
+ def test_patch_rejects_default_email_sender(self, _name: str, kind: str, verified: bool, other_team: bool) -> None:
+ team = Team.objects.create(organization=self.organization, name="other") if other_team else self.team
+ sender = Integration.objects.create(
+ team=team, kind=kind, integration_id="[email protected]", config={"verified": verified}
+ )
+
+ response = self.client.patch(self.url, {"workflows_config": {"default_email_integration_id": sender.id}})
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "workflows_config"
+ stored = TeamWorkflowsConfig.objects.filter(team=self.team).values_list(
+ "default_email_integration_id", flat=True
+ )
+ assert list(stored) in ([], [None])
+
+ def test_patch_sets_and_clears_default_email_sender(self) -> None:
+ sender = Integration.objects.create(
+ team=self.team, kind="email", integration_id="[email protected]", config={"verified": True}
+ )
+
+ response = self.client.patch(self.url, {"workflows_config": {"default_email_integration_id": sender.id}})
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert TeamWorkflowsConfig.objects.get(team=self.team).default_email_integration_id == sender.id
+
+ response = self.client.patch(self.url, {"workflows_config": {"default_email_integration_id": None}})
+ assert response.status_code == status.HTTP_200_OK
+ assert TeamWorkflowsConfig.objects.get(team=self.team).default_email_integration_id is None
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index a83445f5785f..ef0509b25cec 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -435,6 +435,20 @@ describe('broadcastWizardLogic', () => {
expect(logic.values.stepValidationErrors.review).toEqual(expected)
})
+ it('starts a new broadcast with the only verified sender without creating a draft', async () => {
+ const createDraft = jest.fn()
+ useMocks({ post: { '/api/projects/:team_id/hog_flows/': () => createDraft() } })
+ integrationsLogic.mount()
+
+ await expectLogic(logic, () => {
+ integrationsLogic.actions.loadIntegrations()
+ }).toDispatchActions(['defaultSenderApplied'])
+
+ expect(logic.values.email.from).toEqual({ integrationId: 1 })
+ expect(logic.values.stepValidationErrors.content).not.toContain('Choose an email sender')
+ expect(createDraft).not.toHaveBeenCalled()
+ })
+
it('resumes a saved draft on the step in its URL and drops the step from the URL', async () => {
latest = savedBroadcast({ name: 'Spring sale', subject: '', updatedAt: '2026-09-24T10:00:00Z' })
router.actions.push('/broadcasts/broadcast-1', { step: 'content', other: 'kept' })
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
index 5d2cd75295f2..0f66c94273ac 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.ts
@@ -39,6 +39,7 @@ import type {
HogFlowScheduleApi,
} from 'products/workflows/frontend/generated/api.schemas'
+import { resolveDefaultEmailSender } from '../Channels/defaultEmailSender'
import {
DEFAULT_STATE,
ONE_TIME_RRULE,
@@ -263,6 +264,9 @@ export interface broadcastWizardLogicActions {
resourceEdited: (event: ResourceEditedEvent) => {
event: ResourceEditedEvent
} // resourceEditedLogic
+ applyDefaultSender: () => {
+ value: true
+ }
applyExternalEdit: (
broadcast: HogFlowApi,
base: HogFlowApi | null
@@ -279,6 +283,9 @@ export interface broadcastWizardLogicActions {
continueStep: () => {
value: true
}
+ defaultSenderApplied: (integrationId: number) => {
+ integrationId: number
+ }
deleteBroadcast: () => {
value: true
}
@@ -566,6 +573,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
setEmailRateLimit: (emailRateLimit: HogFlowEmailSendingRateLimitApi | null) => ({ emailRateLimit }),
setEmailSettings: (settings: Partial<BroadcastEmailSettings>) => ({ settings }),
setEmail: (email: BroadcastEmailValue) => ({ email }),
+ applyDefaultSender: true,
+ defaultSenderApplied: (integrationId: number) => ({ integrationId }),
setScheduleMode: (mode: BroadcastScheduleMode) => ({ mode }),
setSendAt: (sendAt: string | null) => ({ sendAt }),
setSendAtFromPicker: (pickerDate: string | null) => ({ pickerDate }),
@@ -773,6 +782,8 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
DEFAULT_BROADCAST_EMAIL,
{
setEmail: (_, { email }) => email,
+ defaultSenderApplied: (state, { integrationId }) =>
+ state.from?.integrationId ? state : { ...state, from: { ...state.from, integrationId } },
applyExternalEdit: (state, { broadcast }) => {
const value = findAction(broadcast, 'function_email')?.config?.inputs?.email?.value
return value ? { ...DEFAULT_BROADCAST_EMAIL, ...value } : state
@@ -1142,6 +1153,26 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
}),
listeners(({ actions, values, props, cache }) => ({
+ applyDefaultSender: () => {
+ // Only fills an empty sender on a broadcast that is still being written. It is not an
+ // edit, so it does not autosave; the next save or launch carries it.
+ if (values.email.from?.integrationId || (values.broadcast && values.broadcast.status !== 'draft')) {
+ return
+ }
+ const team = values.currentTeam
+ const sender = resolveDefaultEmailSender(
+ values.integrations,
+ team && 'workflows_config' in team ? team.workflows_config?.default_email_integration_id : null
+ )
+ if (!sender) {
+ return
+ }
+ actions.defaultSenderApplied(sender.integrationId)
+ // pinned: analytics event name
+ posthog.capture('email sender preselected', { surface: 'broadcast', reason: sender.reason })
+ },
+ [integrationsLogic.actionTypes.loadIntegrationsSuccess]: () => actions.applyDefaultSender(),
+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: () => actions.applyDefaultSender(),
expandRun: ({ runId }) => {
actions.setExpandedRunOverride([...values.expandedRunIds.filter((id) => id !== runId), runId])
},
@@ -1741,6 +1772,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
if (values.broadcast?.status !== 'draft') {
return
}
+ actions.applyDefaultSender()
// A draft just saved from /broadcasts/new carries the step it was on, and a composer draft says so.
// Otherwise resume at the first incomplete step; complete drafts land on review.
const { step, [COMPOSER_DRAFT_PARAM]: from, ...searchParams } = router.values.searchParams
@@ -1767,6 +1799,7 @@ export const broadcastWizardLogic = kea<broadcastWizardLogicType>([
actions.loadBroadcast()
return
}
+ actions.applyDefaultSender()
const {
[AUDIENCE_PREFILL_PARAM]: audience,
[NAME_PREFILL_PARAM]: name,
diff --git a/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts b/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts
index 8d8a70dda1ab..c56491edfb95 100644
--- a/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts
+++ b/products/workflows/frontend/Channels/EmailSetup/emailSetupModalLogic.ts
@@ -6,6 +6,7 @@ import { loaders } from 'kea-loaders'
import api, { ApiError } from 'lib/api'
import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { teamLogic } from 'scenes/teamLogic'
import { IntegrationType } from '~/types'
@@ -283,6 +284,8 @@ export const emailSetupModalLogic = kea<emailSetupModalLogicType>([
verifyDomainSuccess: ({ verification }) => {
if (verification?.status === 'success') {
actions.loadIntegrations()
+ // Verifying the first sender makes it the project default on the server.
+ teamLogic.findMounted()?.actions.loadCurrentTeam()
}
},
})),
diff --git a/products/workflows/frontend/Channels/defaultEmailSender.test.ts b/products/workflows/frontend/Channels/defaultEmailSender.test.ts
new file mode 100644
index 000000000000..ce1b0d280f58
--- /dev/null
+++ b/products/workflows/frontend/Channels/defaultEmailSender.test.ts
@@ -0,0 +1,39 @@
+import { IntegrationType } from '~/types'
+
+import { resolveDefaultEmailSender } from './defaultEmailSender'
+
+const sender = (id: number, verified: boolean, kind = 'email'): IntegrationType =>
+ ({ id, kind, config: { verified } }) as unknown as IntegrationType
+
+describe('resolveDefaultEmailSender', () => {
+ it.each([
+ { case: 'the project default', integrations: [sender(1, true), sender(2, true)], defaultId: 2, expected: 2 },
+ {
+ case: 'the only verified sender',
+ integrations: [sender(1, true), sender(2, false)],
+ defaultId: null,
+ expected: 1,
+ },
+ {
+ case: 'nothing when several are verified',
+ integrations: [sender(1, true), sender(2, true)],
+ defaultId: null,
+ expected: null,
+ },
+ { case: 'nothing for an unverified default', integrations: [sender(1, false)], defaultId: 1, expected: null },
+ {
+ case: 'the only verified sender when the default was deleted',
+ integrations: [sender(1, true)],
+ defaultId: 9,
+ expected: 1,
+ },
+ {
+ case: 'nothing for a verified non-email integration',
+ integrations: [sender(1, true, 'slack')],
+ defaultId: 1,
+ expected: null,
+ },
+ ])('picks $case', ({ integrations, defaultId, expected }) => {
+ expect(resolveDefaultEmailSender(integrations, defaultId)?.integrationId ?? null).toEqual(expected)
+ })
+})
diff --git a/products/workflows/frontend/Channels/defaultEmailSender.ts b/products/workflows/frontend/Channels/defaultEmailSender.ts
new file mode 100644
index 000000000000..82f05e42c8f8
--- /dev/null
+++ b/products/workflows/frontend/Channels/defaultEmailSender.ts
@@ -0,0 +1,25 @@
+import { IntegrationType } from '~/types'
+
+export type DefaultEmailSenderReason = 'project_default' | 'only_verified_sender'
+
+export interface DefaultEmailSender {
+ integrationId: number
+ reason: DefaultEmailSenderReason
+}
+
+export function resolveDefaultEmailSender(
+ integrations: IntegrationType[] | null | undefined,
+ defaultIntegrationId: number | null | undefined
+): DefaultEmailSender | null {
+ const verified = (integrations ?? []).filter(
+ (integration) => integration.kind === 'email' && integration.config?.verified === true
+ )
+ const projectDefault = verified.find((integration) => integration.id === defaultIntegrationId)
+ if (projectDefault) {
+ return { integrationId: projectDefault.id, reason: 'project_default' }
+ }
+ if (verified.length === 1) {
+ return { integrationId: verified[0].id, reason: 'only_verified_sender' }
+ }
+ return null
+}
diff --git a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
index 3a1e2cbd3f95..413e6a83be18 100644
--- a/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
+++ b/products/workflows/frontend/Workflows/hogflows/hogFlowEditorLogic.tsx
@@ -14,18 +14,23 @@ import { MakeLogicType, actions, connect, events, kea, key, listeners, path, pro
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
+import posthog from 'posthog-js'
import type { DragEvent, RefObject } from 'react'
import { lemonToast } from '@posthog/lemon-ui'
import { AppMetricsTotalsRequest, loadAppMetricsTotals } from 'lib/components/AppMetrics/appMetricsLogic'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { uuid } from 'lib/utils/dom'
import { objectsEqual, reconcileById } from 'lib/utils/objects'
import { templateToConfiguration } from 'scenes/hog-functions/configuration/hogFunctionConfigurationLogic'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import type { HogFunctionTemplateType, UserBasicType } from '../../../../../frontend/src/types'
+import type { IntegrationType, TeamPublicType, TeamType } from '../../../../../frontend/src/types'
+import { resolveDefaultEmailSender } from '../../Channels/defaultEmailSender'
import { optOutCategoriesLogic } from '../../OptOuts/optOutCategoriesLogic'
import type { MessageCategory } from '../../OptOuts/optOutCategoriesLogic'
import { EXIT_NODE_ID, TRIGGER_NODE_ID, WorkflowLogicProps, workflowLogic } from '../workflowLogic'
@@ -202,8 +207,10 @@ export type CreateActionType = Pick<HogFlowAction, 'type' | 'config' | 'name' |
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface hogFlowEditorLogicValues {
+ integrations: IntegrationType[] | null // integrationsLogic
categories: MessageCategory[] // optOutCategoriesLogic
categoriesLoading: boolean // optOutCategoriesLogic
+ currentTeam: TeamPublicType | TeamType | null // teamLogic
edgesByActionId: Record<string, HogFlowEdge[]> // workflowLogic
hogFunctionTemplatesById: Record<string, HogFunctionTemplateType> // workflowLogic
workflow: HogFlow // workflowLogic
@@ -2187,6 +2194,10 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
['workflow', 'edgesByActionId', 'hogFunctionTemplatesById'],
optOutCategoriesLogic(),
['categories', 'categoriesLoading'],
+ integrationsLogic,
+ ['integrations'],
+ teamLogic,
+ ['currentTeam'],
],
actions: [
workflowLogic,
@@ -2788,6 +2799,34 @@ export const hogFlowEditorLogic = kea<hogFlowEditorLogicType>([
}
}
+ if (!isHogFlowActionNode && 'template_id' in config && config.template_id === 'template-email') {
+ const emailInput = config.inputs?.email
+ const team = values.currentTeam
+ const sender = resolveDefaultEmailSender(
+ values.integrations,
+ team && 'workflows_config' in team
+ ? team.workflows_config?.default_email_integration_id
+ : null
+ )
+ if (sender && emailInput?.value && !emailInput.value.from?.integrationId) {
+ config = {
+ ...config,
+ inputs: {
+ ...config.inputs,
+ email: {
+ ...emailInput,
+ value: {
+ ...emailInput.value,
+ from: { ...emailInput.value.from, integrationId: sender.integrationId },
+ },
+ },
+ },
+ }
+ // pinned: analytics event name
+ posthog.capture('email sender preselected', { surface: 'workflow', reason: sender.reason })
+ }
+ }
+
const newAction = {
id: isHogFlowActionNode
? (values.nodeToBeAdded as HogFlowActionNode).id
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 194392963d55..2ae773030930 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -81700,6 +81700,11 @@ export namespace Schemas {
* @nullable
*/
workflow_task_team_rate_limit_per_day?: number | null;
+ /**
+ * ID of the verified email integration that new broadcasts and workflow email steps use as their sender. Null means no default. Set automatically when the project's first email sender is verified, and cleared when that integration is deleted.
+ * @nullable
+ */
+ default_email_integration_id?: number | null;
}
export interface TeamFeatureFlagPolicyConfig {
diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.ts
index 330e59ec940b..2c832e512eba 100644
--- a/services/mcp/src/generated/core/api.ts
+++ b/services/mcp/src/generated/core/api.ts
@@ -2761,6 +2761,12 @@ export const OrganizationsProjectsCreateBody = () => zod
.describe(
'How many AI tasks all workflows in the project can create together in a rolling 24 hours. Null uses the default of 500; zero pauses task creation for the project. Support raises the limit above 2500.'
),
+ default_email_integration_id: zod
+ .number()
+ .nullish()
+ .describe(
+ "ID of the verified email integration that new broadcasts and workflow email steps use as their sender. Null means no default. Set automatically when the project's first email sender is verified, and cleared when that integration is deleted."
+ ),
})
.optional(),
feature_flag_policy_config: zod
@@ -5474,6 +5480,12 @@ export const OrganizationsProjectsPartialUpdateBody = () => zod
.describe(
'How many AI tasks all workflows in the project can create together in a rolling 24 hours. Null uses the default of 500; zero pauses task creation for the project. Support raises the limit above 2500.'
),
+ default_email_integration_id: zod
+ .number()
+ .nullish()
+ .describe(
+ "ID of the verified email integration that new broadcasts and workflow email steps use as their sender. Null means no default. Set automatically when the project's first email sender is verified, and cleared when that integration is deleted."
+ ),
})
.optional(),
feature_flag_policy_config: zod
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
index 626132ac9548..7d3f60d8cb4d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/project-settings-update.json
@@ -4284,6 +4284,17 @@
"description": "When enabled, workflows engagement activity (email sends, opens, clicks, bounces, spam reports, unsubscribes) is captured as standard PostHog events ($workflows_email_*) alongside the existing workflow metrics.",
"type": "boolean"
},
+ "default_email_integration_id": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "ID of the verified email integration that new broadcasts and workflow email steps use as their sender. Null means no default. Set automatically when the project's first email sender is verified, and cleared when that integration is deleted."
+ },
"email_tracking_consent_mode": {
"description": "Recipient-consent enforcement for open/click tracking on marketing workflow emails. 'off': no enforcement, tracking follows each email step's own setting. 'opt_out': track by default but not recipients who have opted out. 'opt_in': only track recipients who have explicitly opted in. Transactional emails are exempt from consent enforcement.\n\n* `off` - Off\n* `opt_out` - Opt Out\n* `opt_in` - Opt In",
"enum": ["off", "opt_out", "opt_in"],