Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .changeset/node-email-tracking.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
'posthog-node': minor
---

A send with `templateKey` now takes `tracking` and `sensitive`.

`tracking` chooses what PostHog tracks for the email. `tracking: true` turns on opens, clicks and engagement events. `tracking: false` turns them all off. An object such as `{ clicks: true }` or `{ engagement: false }` turns each kind on or off, and a key you leave out keeps its default. Without it, PostHog counts opens, captures engagement events, and counts clicks only when the email isn't sensitive.

`sensitive` marks an email that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `templateKey` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. PostHog refuses `sensitive: false` when the matching template is sensitive. A send that sets neither option works exactly as before.

`captureEngagement` is deprecated in favor of `tracking: { engagement: false }`. It keeps working, but PostHog refuses a send that sets both.

`tracking` and `sensitive` need PostHog's API support, which is rolling out. Until it reaches your PostHog instance, PostHog refuses a send that sets either one.
16 changes: 15 additions & 1 deletion packages/node/references/posthog-node-5.md
Original file line number Diff line number Diff line change
Expand Up @@ -2795,11 +2795,13 @@ Options accepted by `posthog.metrics.count/gauge/histogram`.

| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-captureengagement"></a> `captureEngagement?` | `boolean` | Whether PostHog captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to `true`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting. |
| <a id="property-captureengagement"></a> ~~`captureEngagement?`~~ | `boolean` | Whether PostHog captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to `true`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting. **Deprecated** Use `tracking: { engagement: false }`. It keeps working, but PostHog refuses a send that sets both `captureEngagement` and `tracking`. |
| <a id="property-from"></a> `from?` | `string` | A verified sender, such as `'Acme <security@example.com>'`. Without it, the project's default sender. |
| <a id="property-replyto"></a> `replyTo?` | `string` \| `string`[] | - |
| <a id="property-sensitive"></a> `sensitive?` | `boolean` | Marks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `templateKey` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. PostHog refuses `sensitive: false` when the matching template is sensitive. |
| <a id="property-subject"></a> `subject` | `string` | - |
| <a id="property-templatekey"></a> `templateKey` | `string` | Names the email, such as `'password-reset'`, so its metrics, logs and status group under it in PostHog. Letters, digits, hyphens and underscores, at most 400. |
| <a id="property-tracking"></a> `tracking?` | `boolean` \| `EmailTracking` | What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. - `true` turns on opens, clicks and engagement events. - `false` turns off all tracking, including kinds PostHog adds later. PostHog can't count the email's opens or clicks, and captures no engagement events. - An object turns each kind on or off. A key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. |

### `CodeEmailForm`

Expand Down Expand Up @@ -2957,6 +2959,18 @@ The status of an email that `posthog.emails.send()` queued.
| <a id="property-status"></a> `status` | `EmailDeliveryStatus` \| `string` & `object` | - |
| <a id="property-statusat"></a> `statusAt` | `string` | When the email reached its current status, as an ISO 8601 timestamp. |

### `EmailTracking`

Which kinds of tracking a send with `templateKey` turns on.

#### Properties

| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-clicks"></a> `clicks?` | `boolean` | Counts clicks by sending the email's links through PostHog's click tracking. Defaults to `false` for a sensitive email and `true` for any other. Needs `opens`: PostHog refuses a send with `opens: false` and `clicks: true`. |
| <a id="property-engagement"></a> `engagement?` | `boolean` | Captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to `true`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. |
| <a id="property-opens"></a> `opens?` | `boolean` | Counts opens with PostHog's open pixel. Defaults to `true`. |

### `EmailWarning`

A warning PostHog returned with a queued email.
Expand Down
16 changes: 15 additions & 1 deletion packages/node/references/posthog-node-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -2795,11 +2795,13 @@ Options accepted by `posthog.metrics.count/gauge/histogram`.

| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-captureengagement"></a> `captureEngagement?` | `boolean` | Whether PostHog captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to `true`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting. |
| <a id="property-captureengagement"></a> ~~`captureEngagement?`~~ | `boolean` | Whether PostHog captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to `true`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. A template made in PostHog follows the project's setting. **Deprecated** Use `tracking: { engagement: false }`. It keeps working, but PostHog refuses a send that sets both `captureEngagement` and `tracking`. |
| <a id="property-from"></a> `from?` | `string` | A verified sender, such as `'Acme <security@example.com>'`. Without it, the project's default sender. |
| <a id="property-replyto"></a> `replyTo?` | `string` \| `string`[] | - |
| <a id="property-sensitive"></a> `sensitive?` | `boolean` | Marks the email as sensitive, such as one that carries login links, reset tokens or codes. A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its subject off engagement events, and keeps its content out of PostHog's logs. Without it, a send whose `templateKey` matches a template saved in PostHog follows that template's setting, and any other send is sensitive. PostHog refuses `sensitive: false` when the matching template is sensitive. |
| <a id="property-subject"></a> `subject` | `string` | - |
| <a id="property-templatekey"></a> `templateKey` | `string` | Names the email, such as `'password-reset'`, so its metrics, logs and status group under it in PostHog. Letters, digits, hyphens and underscores, at most 400. |
| <a id="property-tracking"></a> `tracking?` | `boolean` \| `EmailTracking` | What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel, captures engagement events, and counts clicks only when the email isn't sensitive. - `true` turns on opens, clicks and engagement events. - `false` turns off all tracking, including kinds PostHog adds later. PostHog can't count the email's opens or clicks, and captures no engagement events. - An object turns each kind on or off. A key you leave out keeps its default. Turn clicks on for a sensitive email only when its links are safe to send through PostHog's click tracking. |

### `CodeEmailForm`

Expand Down Expand Up @@ -2957,6 +2959,18 @@ The status of an email that `posthog.emails.send()` queued.
| <a id="property-status"></a> `status` | `EmailDeliveryStatus` \| `string` & `object` | - |
| <a id="property-statusat"></a> `statusAt` | `string` | When the email reached its current status, as an ISO 8601 timestamp. |

### `EmailTracking`

Which kinds of tracking a send with `templateKey` turns on.

#### Properties

| Property | Type | Description |
| ------ | ------ | ------ |
| <a id="property-clicks"></a> `clicks?` | `boolean` | Counts clicks by sending the email's links through PostHog's click tracking. Defaults to `false` for a sensitive email and `true` for any other. Needs `opens`: PostHog refuses a send with `opens: false` and `clicks: true`. |
| <a id="property-engagement"></a> `engagement?` | `boolean` | Captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events of the recipient. Defaults to `true`. A project whose admin turned engagement capture off captures nothing, whatever the send asks. |
| <a id="property-opens"></a> `opens?` | `boolean` | Counts opens with PostHog's open pixel. Defaults to `true`. |

### `EmailWarning`

A warning PostHog returned with a queued email.
Expand Down
77 changes: 73 additions & 4 deletions packages/node/src/__tests__/emails.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
import { createElement, type ReactElement, Suspense, use } from 'react'

import { EmailError, PostHog, PostHogOptions, SendEmailOptions } from '@/entrypoints/index.node'
Expand Down Expand Up @@ -186,7 +188,6 @@ describe('emails', () => {
template_key: 'password-reset',
subject: 'Reset your password',
html: '<p>Reset</p>',
capture_engagement: true,
},
],
[
Expand Down Expand Up @@ -223,7 +224,6 @@ describe('emails', () => {
html: '<p>Reset</p>',
text: 'Reset',
reply_to: ['a@example.com', 'b@example.com'],
capture_engagement: true,
},
],
[
Expand All @@ -238,7 +238,6 @@ describe('emails', () => {
template_key: 'password-reset',
subject: 'Reset',
html: '<p>Reset</p>',
capture_engagement: true,
},
],
])('posts content from code with %s to the same send URL', async (_name, content, body) => {
Expand Down Expand Up @@ -296,7 +295,6 @@ describe('emails', () => {
subject: 'Welcome',
html: expect.stringContaining('<p>Welcome, Ada</p>'),
text: 'Welcome, Ada',
capture_engagement: true,
to: 'user@example.com',
},
])
Expand Down Expand Up @@ -916,3 +914,74 @@ describe('emails', () => {
})
})
})

describe('emails over HTTP', () => {
const CODE_SEND = { to: 'user@example.com', templateKey: 'welcome', subject: 'Welcome', html: '<p>Hi</p>' }
const CODE_SEND_BODY = { to: 'user@example.com', template_key: 'welcome', subject: 'Welcome', html: '<p>Hi</p>' }

let server: Server
let posthog: PostHog
let received: unknown[]

beforeAll(async () => {
vi.useRealTimers()
server = createServer((request, response) => {
let body = ''
request.on('data', (chunk) => (body += chunk))
request.on('end', () => {
received.push(JSON.parse(body))
response.writeHead(202, { 'Content-Type': 'application/json' })
response.end(JSON.stringify({ message_id: 'msg_1', replayed: false }))
})
})
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const { port } = server.address() as AddressInfo
posthog = new PostHog('phc_test', {
secretKey: SECRET_KEY,
appHost: `http://127.0.0.1:${port}`,
enableLocalEvaluation: false,
})
})

afterAll(async () => {
await posthog.shutdown()
await new Promise((resolve) => server.close(resolve))
})

beforeEach(() => {
received = []
})

it.each([
['no tracking or sensitive choice, which leaves them and capture_engagement out', {}, {}],
['the email marked sensitive', { sensitive: true }, { sensitive: true }],
['the email marked not sensitive', { sensitive: false }, { sensitive: false }],
['all tracking turned off', { tracking: false }, { tracking: false }],
['all tracking turned on', { tracking: true }, { tracking: true }],
[
'each kind of tracking chosen',
{ tracking: { opens: true, clicks: true, engagement: false } },
{ tracking: { opens: true, clicks: true, engagement: false } },
],
['the deprecated captureEngagement', { captureEngagement: false }, { capture_engagement: false }],
])('delivers a code send with %s', async (_name, options, body) => {
const { data, error } = await posthog.emails.send({ ...CODE_SEND, ...options })

expect(error).toBeNull()
expect(data?.id).toBe('msg_1')
expect(received).toEqual([{ ...CODE_SEND_BODY, ...body }])
})

it.each([
['tracking', { tracking: false }],
['sensitive', { sensitive: false }],
])('refuses %s on the template form without sending', async (field, option) => {
const send = { to: 'user@example.com', templateId: TEMPLATE_ID, ...option } as unknown as SendEmailOptions

const { data, error } = await posthog.emails.send(send)

expect(data).toBeNull()
expect(error).toMatchObject({ code: 'invalid_form', name: 'validation_error', field })
expect(received).toEqual([])
})
})
9 changes: 9 additions & 0 deletions packages/node/src/__tests__/types/emails-forms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ export const forms: SendEmailOptions[] = [
{ to, templateId, templateData: { name: 'Jane' } },
{ to, templateKey: 'reset', subject: 'Reset', html: '<p>Reset</p>', replyTo: ['help@example.com'] },
{ to, templateKey: 'reset', subject: 'Reset', text: 'Reset', from: 'security@example.com', captureEngagement: false },
{ to, templateKey: 'welcome', subject: 'Welcome', html: '<p>Hi</p>', tracking: false },
{ to, templateKey: 'welcome', subject: 'Welcome', html: '<p>Hi</p>', tracking: { clicks: true } },
{ to, templateKey: 'welcome', subject: 'Welcome', html: '<p>Hi</p>', sensitive: false },
{ to, templateKey: 'reset', subject: 'Reset', react },
{ to, templateKey: 'reset', subject: 'Reset', react, text: 'Reset' },
]
Expand All @@ -18,6 +21,12 @@ export const wrongCombinations: SendEmailOptions[] = [
{ to, templateId, templateKey: 'reset', subject: 'Reset', html: '<p>R</p>' },
// @ts-expect-error a template made in PostHog follows the project's engagement capture setting
{ to, templateId, captureEngagement: false },
// @ts-expect-error a template made in PostHog keeps its own tracking
{ to, templateId, tracking: false },
// @ts-expect-error a template made in PostHog keeps its own sensitive setting
{ to, templateId, sensitive: false },
// @ts-expect-error tracking takes only opens, clicks and engagement
{ to, templateKey: 'welcome', subject: 'Welcome', html: '<p>Hi</p>', tracking: { open: false } },
// @ts-expect-error a template made in PostHog keeps its own sender
{ to, templateId, from: 'security@example.com' },
// @ts-expect-error the code form needs html, text or both
Expand Down
8 changes: 6 additions & 2 deletions packages/node/src/emails/emails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ const CODE_FIELDS: EveryField<CodeEmailForm> = {
from: true,
replyTo: true,
captureEngagement: true,
sensitive: true,
tracking: true,
html: true,
text: true,
react: true,
Expand Down Expand Up @@ -408,7 +410,7 @@ function templateContent(send: UncheckedSend, distinctId: string | undefined): R
}

function codeContent(send: UncheckedSend, distinctId: string | undefined): Record<string, unknown> {
const { templateKey, subject, html, text, react, from, replyTo, captureEngagement } = send
const { templateKey, subject, html, text, react, from, replyTo, captureEngagement, sensitive, tracking } = send
if (typeof templateKey !== 'string' || !TEMPLATE_KEY_PATTERN.test(templateKey)) {
throw invalid(
'invalid_template_key',
Expand Down Expand Up @@ -439,7 +441,9 @@ function codeContent(send: UncheckedSend, distinctId: string | undefined): Recor
...(text !== undefined && { text }),
...(from !== undefined && { from }),
...(sendsReplyTo && { reply_to: typeof replyTo === 'string' ? [replyTo] : replyTo }),
capture_engagement: captureEngagement ?? true,
...(captureEngagement !== undefined && { capture_engagement: captureEngagement }),
...(sensitive !== undefined && { sensitive }),
Comment thread
Silthus marked this conversation as resolved.
Resolved
...(tracking !== undefined && { tracking }),
Comment thread
Silthus marked this conversation as resolved.
Resolved
...(distinctId !== undefined && { distinct_id: distinctId }),
}
}
Expand Down
44 changes: 44 additions & 0 deletions packages/node/src/emails/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,52 @@ interface CodeEmailFields {
* bounced) as events of the recipient. Defaults to `true`. A project whose admin turned
* engagement capture off captures nothing, whatever the send asks. A template made in PostHog
* follows the project's setting.
*
* @deprecated Use `tracking: { engagement: false }`. It keeps working, but PostHog refuses a
* send that sets both `captureEngagement` and `tracking`.
*/
captureEngagement?: boolean
/**
* Marks the email as sensitive, such as one that carries login links, reset tokens or codes.
* A sensitive email keeps its links as they are unless `tracking` turns clicks on, leaves its
* subject off engagement events, and keeps its content out of PostHog's logs.
*
* Without it, a send whose `templateKey` matches a template saved in PostHog follows that
* template's setting, and any other send is sensitive. PostHog refuses `sensitive: false` when
* the matching template is sensitive.
*/
sensitive?: boolean
/**
* What PostHog tracks for this email. Without it, PostHog counts opens with its open pixel,
* captures engagement events, and counts clicks only when the email isn't sensitive.
*
* - `true` turns on opens, clicks and engagement events.
* - `false` turns off all tracking, including kinds PostHog adds later. PostHog can't count the
* email's opens or clicks, and captures no engagement events.
* - An object turns each kind on or off. A key you leave out keeps its default.
*
* Turn clicks on for a sensitive email only when its links are safe to send through PostHog's
* click tracking.
*/
tracking?: boolean | EmailTracking
}

/** Which kinds of tracking a send with `templateKey` turns on. */
export interface EmailTracking {
/** Counts opens with PostHog's open pixel. Defaults to `true`. */
opens?: boolean
/**
* Counts clicks by sending the email's links through PostHog's click tracking. Defaults to
* `false` for a sensitive email and `true` for any other. Needs `opens`: PostHog refuses a send
* with `opens: false` and `clicks: true`.
*/
clicks?: boolean
/**
* Captures the email's engagement events (sent, delivered, opened, clicked, bounced) as events
* of the recipient. Defaults to `true`. A project whose admin turned engagement capture off
* captures nothing, whatever the send asks.
*/
engagement?: boolean
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/node/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export type {
EmailReactElement,
Emails,
EmailStatus,
EmailTracking,
EmailWarning,
GetEmailResponse,
SendCodeEmailOptions,
Expand Down
Loading