Examples

These examples cover the transactional emails that most products send. Each one gives the settings to use, how to build its idempotency key, and whether to pass a distinct ID. Then it shows the send.

Each example assumes that you already set up the client from your SDK page, and created the email with the variables that the example sends.

Sign-in code

Send a one-time code when someone signs in without a password.

SettingValue
Template variablescode, expires_in_minutes
Protect sensitive dataOn, so PostHog keeps no copy of the code
Distinct IDThe user's ID
Idempotency keysign-in-code-{code_id}, one key for each code that you issue

liquid
Your sign-in code is {{ variables.code }}. It expires in {{ variables.expires_in_minutes }} minutes.
const { error } = await posthog.emails.send({
to: user.email,
templateId: "<template_id>",
templateData: { code: signInCode.code, expires_in_minutes: 10 },
distinctId: user.id,
idempotencyKey: `sign-in-code-${signInCode.id}`,
})
if (error) {
throw error
}

When the person asks for a new code, issue a new code with a new ID. The new ID makes a new key, so PostHog sends a new email. A retry of the same code sends nothing new.

Email address check

Send a link that confirms that a new user owns their email address.

SettingValue
Template variablesfirst_name, verify_link
Protect sensitive dataOn, so the link's token never goes through a tracking redirect
Distinct IDThe new user's ID. Call identify() with the same ID when the user signs up.
Idempotency keyverify-email-{verification_id}

const { error } = await posthog.emails.send({
to: user.email,
templateId: "<template_id>",
templateData: {
first_name: user.firstName,
verify_link: `https://example.com/verify?token=${verification.token}`,
},
distinctId: user.id,
idempotencyKey: `verify-email-${verification.id}`,
})
if (error) {
throw error
}

Send it from a background job after you save the user, so a slow send never holds up the sign-up. Your SDK page shows a job that retries only the errors that a later attempt can fix.

Team invite

Send an invite to someone who doesn't have an account yet.

“Add a team invite email to our app that sends through PostHog.”

SettingValue
Template variablesinviter_name, team_name, accept_link
Protect sensitive dataOn, because the link carries the invite token
Distinct IDLeave it out. The invitee isn't a user yet, so you have no distinct ID for them.
Idempotency keyinvite-{invite_id}

const { error } = await posthog.emails.send({
to: invite.email,
templateId: "<template_id>",
templateData: {
inviter_name: inviter.name,
team_name: team.name,
accept_link: `https://example.com/invites/${invite.token}`,
},
idempotencyKey: `invite-${invite.id}`,
})
if (error) {
throw error
}

Without a distinct ID, PostHog records the email on a person whose distinct ID is the email address. To resend an invite, issue a new invite with a new ID.

Receipt with a PDF

Send a receipt with the invoice attached, and a copy to the customer's billing contact. Attachments and copies work only with content from your code, so your code renders the email.

SettingValue
Template keyreceipt
Copiescc to the customer's billing contact
AttachmentThe invoice PDF. See the limits.
Distinct IDThe customer's user ID
Idempotency keyreceipt-{order_id}

import { readFile } from "node:fs/promises"
const { error } = await posthog.emails.send({
to: order.customer.email,
templateKey: "receipt",
subject: `Your receipt for order ${order.number}`,
html,
cc: order.customer.billingEmail,
attachments: [
{ filename: `invoice-${order.number}.pdf`, content: await readFile(invoicePath), contentType: "application/pdf" },
],
distinctId: order.customer.userId,
idempotencyKey: `receipt-${order.id}`,
})
if (error) {
throw error
}

The SDKs hash and upload the file for you, and upload nothing when PostHog already has it. With the API, the script does these steps itself. It needs bash, curl, shasum, and jq. On Linux without shasum, use sha256sum "$FILE" in its place. See send files with the API for each step.

Send from a job queue

Send from a job queue when the email shouldn't slow down the request, such as an email address check after a sign-up. Let the queue own the retries:

  • Turn off the client's own retries, so that it doesn't retry inside the job.
  • Keep the idempotency key the same on every attempt.
  • Finish the retries within 7 days. PostHog keeps an idempotency key for 7 days, so a later retry can send the email twice.
  • Retry only the codes that a later attempt can fix: network_error, idempotency_key_in_flight, throttled, and delivery_unavailable. Every other code fails the same way again.

Each tab uses a queue that is common for its language. Rust has no such queue, so its tab shows the pattern without one.

import { Queue } from "bullmq"
const emails = new Queue("emails", { connection: { host: "localhost", port: 6379 } })
await emails.add(
"password-reset",
{ userId, email, resetLink, resetRequestId },
{ attempts: 5, backoff: { type: "exponential", delay: 10_000 } }
)
// The worker sends the email:
import { UnrecoverableError, Worker } from "bullmq"
// A later attempt can fix these. Any other code fails the same way again.
const RETRYABLE_CODES = new Set(["network_error", "idempotency_key_in_flight", "throttled", "delivery_unavailable"])
new Worker(
"emails",
async (job) => {
const { userId, email, resetLink, resetRequestId } = job.data
const { data, error } = await posthog.emails.send({
to: email,
templateKey: "password-reset",
subject: "Reset your password",
html: `<p>Reset your password <a href="${resetLink}">here</a>.</p>`,
distinctId: userId,
// The same key on every attempt, so a retried job never sends the email twice
idempotencyKey: `password-reset-${resetRequestId}`,
// BullMQ retries the job, so the client doesn't retry on its own
maxRetries: 0,
})
if (error) {
throw RETRYABLE_CODES.has(error.code) ? error : new UnrecoverableError(`${error.code}: ${error.message}`)
}
return data.id
},
{ connection: { host: "localhost", port: 6379 } }
)

Measure whether an email works

Each send lands on the recipient's person, so you can measure what people do after an email with the rest of your product data. First, turn on engagement events for your project.

For example, to see how many people finish a password reset after they get the email, build a funnel with these steps:

  1. $workflows_email_delivered, filtered to $email_template_id equals your reset email's template ID. For an email your code writes, filter on $email_template_key instead.
  2. Your own event for a finished reset, such as password_reset_completed.

Filter on the template, not on $email_subject, because a sensitive email's events leave out the subject. And use $workflows_email_delivered as the first step, not $workflows_email_link_clicked: a sensitive email doesn't track clicks by default, so a click step counts nobody.

For this funnel to work, pass the same distinct ID in the send and in the event that your app captures.

Still have questions?

Was this page useful?