Skip to content
Closed
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
5 changes: 5 additions & 0 deletions .changeset/node-emails-get.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'posthog-node': minor
---

Add `posthog.emails.get(id)` to read the latest status of an email that `posthog.emails.send()` queued.
47 changes: 46 additions & 1 deletion packages/node/references/posthog-node-references-latest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2206,7 +2206,7 @@
"name": "EmailError",
"properties": [
{
"description": "PostHog's error code, such as `invalid_recipient`, or one of the SDK's own: `missing_secret_key`, `missing_app_host`, `client_disabled`, `client_closed`, `network_error`, `api_error` for an answer without a code, `unexpected_error`, and `invalid_form`, `invalid_template_id`, `invalid_template_key`, `invalid_attachment` and `invalid_idempotency_key` for a send the SDK refused before any request.",
"description": "PostHog's error code, such as `invalid_recipient`, or one of the SDK's own: `missing_secret_key`, `missing_app_host`, `client_disabled`, `client_closed`, `network_error`, `api_error` for an answer without a code, `unexpected_error`, `invalid_form`, `invalid_template_id`, `invalid_template_key`, `invalid_attachment` and `invalid_idempotency_key` for a send the SDK refused before any request, and `invalid_message_id` for a read.",
"type": "string",
"name": "code"
},
Expand Down Expand Up @@ -2260,6 +2260,44 @@
"properties": [],
"path": "src/emails.ts"
},
{
"id": "EmailStatus",
"name": "EmailStatus",
"properties": [],
"path": "src/emails.ts",
"example": "\"queued\" | \"waiting\" | \"unknown\" | \"skipped\" | \"failed\" | \"sent\" | \"delivered\" | \"bounced\" | \"complained\""
},
{
"id": "EmailStatusRecord",
"name": "EmailStatusRecord",
"properties": [
{
"description": "When PostHog queued the email, as an ISO 8601 timestamp.",
"type": "string",
"name": "createdAt"
},
{
"description": "The `id` that `posthog.emails.send()` returned.",
"type": "string",
"name": "id"
},
{
"description": "Why the email was skipped, failed or bounced, when PostHog knows.",
"type": "string",
"name": "reason"
},
{
"type": "EmailStatus",
"name": "status"
},
{
"description": "When the email reached its status, as an ISO 8601 timestamp.",
"type": "string",
"name": "statusAt"
}
],
"path": "src/emails.ts"
},
{
"id": "EmailTag",
"name": "EmailTag",
Expand Down Expand Up @@ -2789,6 +2827,13 @@
"path": "src/types.ts",
"example": "string | number | (string | number)[] | boolean"
},
{
"id": "GetEmailResult",
"name": "GetEmailResult",
"properties": [],
"path": "src/emails.ts",
"example": "{\n data: EmailStatusRecord;\n error: null;\n} | {\n data: null;\n error: EmailError;\n}"
},
{
"id": "GetFlagsResult",
"name": "GetFlagsResult",
Expand Down
108 changes: 108 additions & 0 deletions packages/node/src/__tests__/emails.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,114 @@ describe('emails', () => {
})
})

describe('get', () => {
const MESSAGE_ID = '0192a7c4-5e2f-7d1a-8b3c-4d5e6f708192'
const STATUS = `GET /api/projects/@current/messaging/emails/${MESSAGE_ID}/`

it('reads the status of an email from the app host with the secret key', async () => {
api.recordStatus({
id: MESSAGE_ID,
status: 'bounced',
created_at: '2026-10-22T08:00:00Z',
status_at: '2026-10-22T08:00:05Z',
reason: 'mailbox_full',
})

const result = await createClient({ migratedFrom: 'resend' }).emails.get(MESSAGE_ID)

expect(result).toEqual({
data: {
id: MESSAGE_ID,
status: 'bounced',
createdAt: '2026-10-22T08:00:00Z',
statusAt: '2026-10-22T08:00:05Z',
reason: 'mailbox_full',
},
error: null,
})
expect(requestLog()).toEqual([STATUS])
expect(api.received[0]).toEqual(
expect.objectContaining({
origin: APP_HOST,
headers: expect.objectContaining({
authorization: `Bearer ${SECRET_KEY}`,
'user-agent': 'posthog-node/1.2.3',
'x-posthog-migrated-from': 'resend',
}),
})
)
})

it('leaves out a reason PostHog did not give', async () => {
api.recordStatus({ id: MESSAGE_ID, status: 'sent', created_at: 'a', status_at: 'b' })

const result = await createClient().emails.get(MESSAGE_ID)

expect(result.data).toEqual({ id: MESSAGE_ID, status: 'sent', createdAt: 'a', statusAt: 'b' })
})

it.each([
['an unknown or new email', undefined, 'not_found'],
[
'an unavailable pipeline',
{ status: 503, body: refusalBody('delivery_unavailable', null) },
'delivery_unavailable',
],
['a throttled read', { status: 429, body: refusalBody('throttled', null) }, 'throttled'],
['a network failure', { networkError: new Error('ECONNRESET') }, 'network_error'],
['an answer without a status', { status: 200, body: { id: MESSAGE_ID } }, 'api_error'],
] satisfies [string, Fault | undefined, string][])(
'returns %s as the error, without a retry',
async (_, fault, code) => {
if (fault) {
api.failNext(fault, Infinity)
}

const result = await createClient().emails.get(MESSAGE_ID)

expect(result).toEqual({ data: null, error: expect.objectContaining({ code }) })
expect(api.received).toHaveLength(1)
}
)

it.each([
['missing_secret_key', 'missing_api_key', { secretKey: undefined }, MESSAGE_ID, 'hog_flow:read'],
['missing_app_host', 'application_error', { appHost: undefined }, MESSAGE_ID, 'appHost'],
['client_disabled', 'application_error', { disabled: true }, MESSAGE_ID, 'disabled'],
['invalid_message_id', 'validation_error', {}, '', 'id'],
['invalid_message_id', 'validation_error', {}, 'message-\uD800', 'id'],
['invalid_message_id', 'validation_error', {}, '.', 'id'],
['invalid_message_id', 'validation_error', {}, '..', 'id'],
])('returns %s as %s without a request', async (code, name, clientOptions: PostHogOptions, id, says) => {
const result = await createClient(clientOptions).emails.get(id)

expect(result).toEqual({
data: null,
error: expect.objectContaining({ name, code, message: expect.stringContaining(says) }),
})
expect(api.received).toEqual([])
})

it('returns client_closed as application_error after shutdown without a request', async () => {
const client = createClient()
await client.shutdown()

const result = await client.emails.get(MESSAGE_ID)

expect(result).toEqual({
data: null,
error: expect.objectContaining({ name: 'application_error', code: 'client_closed' }),
})
expect(api.received).toEqual([])
})

it('reads an id with reserved characters as one path segment', async () => {
await createClient().emails.get('a/b?c')

expect(requestLog()).toEqual(['GET /api/projects/@current/messaging/emails/a%2Fb%3Fc/'])
})
})

describe('errors', () => {
it.each([
[400, 'invalid_recipient', 'validation_error'],
Expand Down
21 changes: 20 additions & 1 deletion packages/node/src/__tests__/utils/fake-emails-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { emailContentHash } from '@/email-content-hash'

const SEND_PATH = '/api/projects/@current/messaging/send/email/'
const UPLOAD_PATH = /^\/api\/projects\/@current\/messaging_templates\/by_key\/([^/]+)\/$/
const STATUS_PATH = /^\/api\/projects\/@current\/messaging\/emails\/([^/]+)\/$/
const DOCS_URL = 'https://posthog.com/docs/workflows/transactional-email-api'

export interface ReceivedRequest {
Expand All @@ -25,6 +26,14 @@ export interface DeliveredEmail {
distinctId?: string
}

export interface StatusRecord {
id: string
status: string
created_at: string
status_at: string
reason?: string
}

interface LocalTemplate {
subject: string
html: string
Expand All @@ -47,14 +56,15 @@ interface ScheduledFault {
/**
* An in-memory PostHog app host that speaks the send and upload routes of the transactional email API: a template by
* id, rendered content by `template_key`, and a local template by key and content hash, which answers
* `template_outdated` until an upload publishes that content. An idempotency key PostHog already accepted for the
* `template_outdated` until an upload publishes that content. It answers the status of an email it was told about. An idempotency key PostHog already accepted for the
* same request answers the first `202` again.
*/
export class FakeEmailsApi {
readonly received: ReceivedRequest[] = []
readonly delivered: DeliveredEmail[] = []
private readonly templateIds = new Set<string>()
private readonly localTemplates = new Map<string, LocalTemplate>()
private readonly statuses = new Map<string, StatusRecord>()
private readonly accepted = new Map<string, { fingerprint: string; messageId: string }>()
private readonly faults: ScheduledFault[] = []
private nextId = 1
Expand Down Expand Up @@ -85,6 +95,10 @@ export class FakeEmailsApi {
this.localTemplates.set(key, { ...content, contentHash: 'v1:edited', editedInPostHog: true })
}

recordStatus(record: StatusRecord): void {
this.statuses.set(record.id, record)
}

localTemplate(key: string): LocalTemplate | undefined {
return this.localTemplates.get(key)
}
Expand Down Expand Up @@ -119,6 +133,11 @@ export class FakeEmailsApi {
if (request.method === 'POST' && request.path === SEND_PATH) {
return this.handleSend(request)
}
const messageId = STATUS_PATH.exec(request.path)?.[1]
if (request.method === 'GET' && messageId) {
const record = this.statuses.get(decodeURIComponent(messageId))
return record ? respond(200, record) : refusal(404, 'not_found', null)
}
return refusal(404, 'not_found', null)
}

Expand Down
4 changes: 2 additions & 2 deletions packages/node/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3067,10 +3067,10 @@ export abstract class PostHogBackendClient extends PostHogCoreStateless implemen

/** One attempt: `posthog.emails` retries on its own, with the same idempotency key. */
private async _requestEmailsApi(
method: 'POST' | 'PUT',
method: 'GET' | 'POST' | 'PUT',
url: string,
headers: Record<string, string>,
body: string
body: string | undefined
): Promise<PostHogApiResponse> {
try {
return await this.requestJson(url, { method, headers, body })
Expand Down
Loading
Loading