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(cdp): send cc and bcc on a transactional code send (#127985)

Michael Reichenbach76019976d8c6
diff --git a/nodejs/src/cdp/cdp-api.serial.test.ts b/nodejs/src/cdp/cdp-api.serial.test.ts
index b24fe27c6dfc..eb8786683717 100644
--- a/nodejs/src/cdp/cdp-api.serial.test.ts
+++ b/nodejs/src/cdp/cdp-api.serial.test.ts
@@ -2358,6 +2358,11 @@ describe('CDP API', () => {
['transactional_email', body],
['transactional_email/send', { ...body, send: codeSend }],
],
+ [
+ 'a changed cc',
+ ['transactional_email/send', { ...body, send: { ...codeSend, cc: ['[email protected]'] } }],
+ ['transactional_email/send', { ...body, send: { ...codeSend, cc: ['[email protected]'] } }],
+ ],
] as const)(
'rejects the key for a request with %s',
async (_desc, [firstRoute, first], [route, payload]) => {
@@ -2421,6 +2426,10 @@ describe('CDP API', () => {
{ ...codeSend, content: { subject: 'Hi', html: '<img src="https://example.com/a.png" alt="Hi">' } },
],
['a code send for a local template', { tracking: { captureEngagement: false } }],
+ [
+ 'a code send with copies to addresses that use atext symbols',
+ { ...codeSend, cc: ['[email protected]'], bcc: ['[email protected]'] },
+ ],
])('stamps %s on the queued run', async (_desc, acceptedSend) => {
const res = await sendAccepted(hogFlow.id, { ...body, send: acceptedSend })
@@ -2469,6 +2478,10 @@ describe('CDP API', () => {
['content with an empty subject', { ...codeSend, content: { subject: '', text: 'Hi' } }],
['a sender without an integration', { ...codeSend, from: { email: '[email protected]' } }],
['no tracking choice', { content: codeSend.content }],
+ [
+ 'more than 10 cc addresses',
+ { ...codeSend, cc: Array.from({ length: 11 }, (_, i) => `copy-${i}@example.com`) },
+ ],
])('refuses a code send with %s', async (_desc, acceptedSend) => {
const invalidBefore = await outcomeCount('invalid_request')
@@ -2479,6 +2492,38 @@ describe('CDP API', () => {
expect(mockQueueInvocations).not.toHaveBeenCalled()
})
+ it.each([
+ [
+ 'a bcc address is suppressed',
+ 'recipient_suppressed',
+ { bcc: ['[email protected]'] },
+ () =>
+ jest
+ .spyOn(api['emailSuppressionService'], 'isSuppressed')
+ .mockImplementation((_teamId, email) => Promise.resolve(email === '[email protected]')),
+ ],
+ [
+ "a cc address's domain has no mail servers",
+ 'recipient_unreachable',
+ { cc: ['[email protected]'] },
+ () =>
+ jest
+ .spyOn(api['emailValidationService'], 'getRecipientSkipReason')
+ .mockImplementation((_teamId, email) =>
+ Promise.resolve(email === '[email protected]' ? 'Skipping send: no mail servers.' : null)
+ ),
+ ],
+ ['a cc address is malformed', 'recipient_unreachable', { cc: ['copy@ph\u3002example.com'] }, () => {}],
+ ] as const)('refuses the whole code send when %s', async (_desc, code, copies, refuse) => {
+ refuse()
+
+ const res = await sendAccepted(hogFlow.id, { ...body, send: { ...codeSend, ...copies } })
+
+ expect(res.status).toEqual(422)
+ expect(res.body).toEqual({ error: code })
+ expect(mockQueueInvocations).not.toHaveBeenCalled()
+ })
+
it.each<[string, () => { payload: Record<string, unknown>; verify?: () => void }]>([
[
'the team is over its email quota',
diff --git a/nodejs/src/cdp/cdp-api.ts b/nodejs/src/cdp/cdp-api.ts
index b73f70012b1a..b21392779e99 100644
--- a/nodejs/src/cdp/cdp-api.ts
+++ b/nodejs/src/cdp/cdp-api.ts
@@ -61,6 +61,8 @@ import {
TransactionalEmailRequest,
TransactionalEmailRequestSchema,
TransactionalEmailStageTimer,
+ isRecipientFormatIssue,
+ transactionalEmailRecipients,
transactionalEmailRequestsTotal,
} from './services/hogflows/transactional-email'
import { InvocationResultsService } from './services/invocation-results.service'
@@ -1210,7 +1212,7 @@ export class CdpApi {
if (!parsed.success) {
const issues = parsed.error.issues
// Signup accepts some addresses this check refuses, and no retry can fix an address.
- if (issues.every((issue) => issue.path[0] === 'to' && issue.code === 'invalid_format')) {
+ if (issues.every(isRecipientFormatIssue)) {
return reply('recipient_unreachable', 422, { error: 'recipient_unreachable' })
}
// Paths and codes only: the values include the recipient's address.
@@ -1309,7 +1311,11 @@ export class CdpApi {
}
try {
stages.start('checks')
- const refusal = await this.refuseTransactionalEmail(team.id, hogFlow, to)
+ const refusal = await this.refuseTransactionalEmail(
+ team.id,
+ hogFlow,
+ transactionalEmailRecipients(parsed.data)
+ )
if (refusal) {
if (idempotencyKey) {
stages.start('idempotency')
@@ -1368,7 +1374,7 @@ export class CdpApi {
private async refuseTransactionalEmail(
teamId: number,
hogFlow: HogFlow,
- to: string
+ recipients: string[]
): Promise<{ outcome: TransactionalEmailOutcome; status: number } | null> {
if (hogFlow.status !== 'active') {
return { outcome: 'not_sendable', status: 400 }
@@ -1377,12 +1383,16 @@ export class CdpApi {
// order wins. The MX check's DNS lookup runs even when an earlier check refuses, which is acceptable because
// refusals are rare and the verdict is cached per domain.
const suspension = this.teamWorkflowsConfigService.getEmailSendingSuspension(teamId)
- const suppressed = this.emailSuppressionService.isSuppressed(teamId, to, { transactional: true })
+ const suppressed = Promise.all(
+ recipients.map((email) => this.emailSuppressionService.isSuppressed(teamId, email, { transactional: true }))
+ )
const quota = checkHogFlowQuotaLimits(hogFlow, teamId, this.deps.quotaLimiting)
// A DNS failure lets the send through.
- const recipientSkipReason = this.emailValidationService.getRecipientSkipReason(teamId, to)
+ const recipientSkipReasons = Promise.all(
+ recipients.map((email) => this.emailValidationService.getRecipientSkipReason(teamId, email))
+ )
// An earlier refusal returns before the later lookups are awaited, so their failures must not go unhandled.
- const lookups: Promise<unknown>[] = [suspension, suppressed, quota, recipientSkipReason]
+ const lookups: Promise<unknown>[] = [suspension, suppressed, quota, recipientSkipReasons]
for (const lookup of lookups) {
lookup.catch(() => undefined)
}
@@ -1393,13 +1403,13 @@ export class CdpApi {
if (hogFlow.email_sending_paused_at) {
return { outcome: 'sending_paused', status: 422 }
}
- if (await suppressed) {
+ if ((await suppressed).some(Boolean)) {
return { outcome: 'recipient_suppressed', status: 422 }
}
if ((await quota).isLimited) {
return { outcome: 'quota_limited', status: 429 }
}
- if (await recipientSkipReason) {
+ if ((await recipientSkipReasons).some(Boolean)) {
return { outcome: 'recipient_unreachable', status: 422 }
}
return null
diff --git a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
index a17da3387f1c..465e70a8ade0 100644
--- a/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
+++ b/nodejs/src/cdp/services/hogflows/hogflow-executor.service.test.ts
@@ -3362,6 +3362,8 @@ describe('Hogflow Executor', () => {
content: { subject: 'Reset your password', html: '<p>Hi {{ variables.name }}</p>', text: 'Hi' },
from: { integrationId, email: '[email protected]', name: 'Security' },
+ bcc: ['[email protected]'],
tracking: { captureEngagement: true },
})
@@ -3610,14 +3612,15 @@ if (not res.success) { throw Error(res.error) }`,
expected: () => ({ type: 'email', ...storedStep() }),
},
{
- name: "a code send with the caller's content, sender and reply-to over the step",
+ name: "a code send with the caller's content, sender, reply-to and copies over the step",
step: codeKeyStep,
send: codeSend,
expected: () => ({
type: 'email',
to: { email: '[email protected]', name: 'Recipient' },
from: { integrationId, email: '[email protected]', name: 'Security' },
subject: 'Reset your password',
preheader: '',
diff --git a/nodejs/src/cdp/services/hogflows/transactional-email.ts b/nodejs/src/cdp/services/hogflows/transactional-email.ts
index 1577b5d207a4..cf0582f5f63b 100644
--- a/nodejs/src/cdp/services/hogflows/transactional-email.ts
+++ b/nodejs/src/cdp/services/hogflows/transactional-email.ts
@@ -3,6 +3,17 @@ import { z } from 'zod'
import { CyclotronInvocationQueueParametersEmailType } from '~/cdp/schema/cyclotron'
+export const MAX_COPY_RECIPIENTS = 10
+
+export const RECIPIENT_ADDRESS_PATTERN =
+ /^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/
+
+const CopyRecipientsSchema = z
+ .array(z.string().email({ pattern: RECIPIENT_ADDRESS_PATTERN }))
+ .max(MAX_COPY_RECIPIENTS)
+ .readonly()
+ .optional()
+
export const AcceptedSendSchema = z
.object({
content: z
@@ -25,6 +36,8 @@ export const AcceptedSendSchema = z
.readonly()
.optional(),
replyTo: z.array(z.string()).readonly().optional(),
+ cc: CopyRecipientsSchema,
+ bcc: CopyRecipientsSchema,
tracking: z.object({ captureEngagement: z.boolean() }).strict().readonly(),
})
.strict()
@@ -43,11 +56,10 @@ export const acceptedSendEmailFields = (
}),
...(send?.from && { from: { ...send.from } }),
...(send?.replyTo && { replyTo: send.replyTo.join(', ') }),
+ ...(send?.cc && { cc: send.cc.join(', ') }),
+ ...(send?.bcc && { bcc: send.bcc.join(', ') }),
})
-export const RECIPIENT_ADDRESS_PATTERN =
- /^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/
-
// What Django sends to run a transactional email's workflow once.
export const TransactionalEmailRequestSchema = z.object({
to: z.string().email({ pattern: RECIPIENT_ADDRESS_PATTERN }),
@@ -66,6 +78,16 @@ export const AcceptedSendRequestSchema = TransactionalEmailRequestSchema.extend(
export type TransactionalEmailRequest = z.infer<typeof TransactionalEmailRequestSchema> & { send?: AcceptedSend }
+export const transactionalEmailRecipients = ({ to, send }: TransactionalEmailRequest): string[] => [
+ to,
+ ...(send?.cc ?? []),
+ ...(send?.bcc ?? []),
+]
+
+export const isRecipientFormatIssue = (issue: z.core.$ZodIssue): boolean =>
+ issue.code === 'invalid_format' &&
+ (issue.path[0] === 'to' || (issue.path[0] === 'send' && (issue.path[1] === 'cc' || issue.path[1] === 'bcc')))
+
export type TransactionalEmailOutcome =
| 'queued'
| 'replayed'
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
index ac4a0ca18511..95eb40617b1b 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.test.ts
@@ -401,21 +401,37 @@ describe('RecipientPreferencesService', () => {
// Suppressed cc and bcc addresses are removed at send time, and a deliverable cc address
// replaces a suppressed `to`. The step is skipped only when no cc address is left.
it.each([
- ['a suppressed cc', '[email protected]', { cc: '[email protected]' }, null],
- ['a suppressed bcc', '[email protected]', { bcc: '[email protected]' }, null],
+ ['a suppressed cc', '[email protected]', { cc: '[email protected]' }, {}, null],
+ ['a suppressed bcc', '[email protected]', { bcc: '[email protected]' }, {}, null],
[
'a suppressed to with a deliverable cc',
{ cc: '[email protected]' },
+ {},
null,
],
[
'a suppressed to with only bcc left',
{ bcc: '[email protected]' },
+ {},
'suppressed',
],
- ] as const)('handles %s', async (_label, to, extraInputs, expected) => {
+ [
+ "a suppressed to with a code send's deliverable cc",
+ {},
+ { cc: ['[email protected]'] },
+ null,
+ ],
+ [
+ "a suppressed to with only a code send's bcc left",
+ {},
+ { bcc: ['[email protected]'] },
+ 'suppressed',
+ ],
+ ] as const)('handles %s', async (_label, to, extraInputs, copies, expected) => {
await insertSuppressionRow('[email protected]')
await insertSuppressionRow('[email protected]')
await insertSuppressionRow('[email protected]')
@@ -424,6 +440,7 @@ describe('RecipientPreferencesService', () => {
// Inject the cc/bcc into the resolved invocation inputs (this is what the
// executor sees at send time after template resolution).
Object.assign(invocation.state.globals!.inputs!.email as object, extraInputs)
+ invocation.state.send = { tracking: { captureEngagement: false }, ...copies }
mockRecipientsManagerGet.mockResolvedValue(null)
const result = await service.shouldSkipAction(invocation, action)
diff --git a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
index 6bf19cb6b079..01e19ae67a4f 100644
--- a/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
+++ b/nodejs/src/cdp/services/messaging/recipient-preferences.service.ts
@@ -1,4 +1,5 @@
import { HogFlowAction } from '~/cdp/schema/hogflow'
+import { acceptedSendEmailFields } from '~/cdp/services/hogflows/transactional-email'
import { RedisV2 } from '~/common/redis/redis-v2'
import { logger } from '~/common/utils/logger'
@@ -155,7 +156,10 @@ export class RecipientPreferencesService {
// Skip only when `to` is suppressed and no cc address can take its place. EmailService
// removes the other suppressed addresses at send time, and the email still goes to the rest.
- const emailInputs = invocation.state.globals.inputs?.email
+ const emailInputs = {
+ ...invocation.state.globals.inputs?.email,
+ ...acceptedSendEmailFields(invocation.state.send),
+ }
try {
const result = await removeSuppressedRecipients(
{