Send emails from code

Your server sends a transactional email with one call: the recipient, the subject, and the HTML. PostHog checks it, sends it, and records what happens next on the person, next to everything else they do in your product.

This page covers how that works, and the fields every send takes. For your language's setup, see its SDK page.

How a send works

  1. Your server calls PostHog with a project secret API key, through an SDK or the API.
  2. PostHog checks the send: the key, the email, and the recipient. It refuses a suppressed or unreachable address, or a paused email, at once with an error code.
  3. PostHog queues it and returns 202 with a message ID. That means queued, not delivered.
  4. The email goes out ahead of marketing emails. It never waits for your sending allowance, but it counts toward it.
  5. The status moves on: sent, then delivered, bounced, or complained. You can check it for 30 days.
  6. Events land on the person: sent, delivered, opened, clicked, and so on, if engagement events are on.

To learn why 202 means queued, and how PostHog retries a send without sending it twice, see how PostHog delivers messages reliably.

Create an API key

Send with a project secret API key that has the Transactional email scope.

  1. Go to Project secret API keys and click Create project secret API key.
  2. Set Transactional email to Write.
  3. Copy the key. It starts with phs_, and you only see it once.
The Create project secret API key form, with Transactional email set to Write

The key can send emails, upload attachments, and read the status of a send. Keep it on your server, and never ship it to the browser. For a service that only reads statuses, set the scope to Read.

Send the HTML

The email lives in your code. Name it with template_key, and send the subject and the HTML that your code builds:

const { data, error } = await posthog.emails.send({
to: "ada@example.com",
templateKey: "password-reset",
subject: "Reset your password",
html,
distinctId: "user_123",
idempotencyKey: "password-reset-8f14e45f",
})

FieldRequiredWhat it does
template_keyYesNames the email, such as password-reset. Use the same key every time, because PostHog groups its sends and metrics under it. Letters, digits, -, and _, up to 256 characters.
toYesThe recipient.
subjectYesThe subject.
html or textOne of themThe body, up to 5 MiB each. PostHog sends it as written. Leave out text and PostHog makes it from html.
distinct_idNoThe user's distinct ID, so the send lands on their person.
fromNoSuch as Hedgebox <security@example.com>, on a verified domain. Defaults to the project's default sender, or its only verified sender.
reply_toNoUp to 10 addresses.
ccNoUp to 10 addresses that get a copy. Plain addresses only, with no names.
bccNoUp to 10 addresses that get a hidden copy. Plain addresses only, with no names.
attachmentsNoFiles to attach. See attachments.
sensitiveNoSee sensitive data and tracking.
trackingNoTurn opens, clicks, and engagement events on or off.
headersNoUp to 8 email headers to add, such as {"X-Entity-Ref-ID": "order-1234"}. See headers and tags.
tagsNoUp to 10 names and values, such as {"plan": "pro"}, to break down the email's events by. See headers and tags.
Idempotency-Key headerNoSend one so a retry never sends the email twice. Send it as a header, not in the body. See retries and errors.

A request has template_id or template_key, not both. A project can have up to 1,000 keys, so use one key for each kind of email, never one for each recipient.

To let your team change an email without a deploy, keep it as a template in PostHog instead, and send its template ID. Both get the same checks, statuses, events, and metrics.

“Move our transactional emails to send through PostHog, keeping the HTML in our code.”

Headers and tags

Only a send with template_key takes headers and tags. Both are objects of names to string values.

  • headers: In-Reply-To, References, List-Unsubscribe, List-Unsubscribe-Post, List-Id, and any header that starts with X-, except X-PostHog- and X-SES-. A value has up to 870 ASCII characters and no line breaks. Only an X- header takes other characters, up to 200 bytes of UTF-8. When PostHog sets a header itself, such as List-Unsubscribe on marketing email, PostHog's value wins.
  • tags: a name has 1 to 64 letters, digits, _, or -, and starts with a letter or a digit. A value has 1 to 256 of the same characters. Each of the email's engagement events carries them in $email_tags, so you can break down by a property such as $email_tags.plan.

See it in PostHog

Each key shows up on the Transactional emails tab after its first send, with its sends and metrics. Click Link source file to link the email to the file in your repo that sends it. Then Copy prompt for your agent tells your coding agent which email to change, and where.

A code email's page in PostHog, with its linked source file and the Copy prompt for your agent button

“How did our password-reset email do last week, and how many people finished resetting their password?”

Send the distinct ID you pass to identify(), usually your user's ID. The send and its events then land on that user's person, in the same timeline as their product events, and the Log shows what they did around it.

  • No distinct ID: PostHog records the email on a person whose distinct ID is the email address. That's a different person from your user, unless you identify users by email.
  • Not a user yet: for an invite, or an address check before sign-up, leave it out.

Email engagement events

Turn on engagement events, and each send records $workflows_email_sent, $workflows_email_delivered, $workflows_email_opened, $workflows_email_link_clicked, $workflows_email_bounced, $workflows_email_blocked (marked as spam), and $workflows_email_failed on the person.

Each event carries $email_to, $email_subject, and the $email_template_id or $email_template_key of the send. A sensitive email's events leave out the subject. Use the events in funnels and insights, such as how many people finish a password reset after the email. They count toward your event usage.

Without engagement events, you still get statuses, the Log, and metrics.

Rules transactional emails follow

  • No opt-outs or frequency cap. Only the suppression list blocks them, after a hard bounce or an API suppression with reason bounce. Use them only for emails a person needs, never for marketing. See marketing vs. transactional email.
  • They can pause. If an email gets too many bounces or complaints, PostHog pauses it, and sends return sending_paused.
  • Rate limits. Each project has a limit on requests per minute and per hour. See API and SDK limits, and how to handle a rate limit.
  • Billing. Billed like other emails. See pricing.

Checks

PostHog sends nothing when one of these checks fails. Each returns 400.

CodeCause
sender_not_verifiedThe project has no verified sender, no verified sender can send from from, or the default sender isn't verified.
sender_requiredThere's no from and no default sender, and the project has more than one verified sender. Send from, or set a default sender.
sandbox_fields_unsupportedThe project has no verified domain, so the test sender sends the email, and the send has cc, bcc, attachments, headers, tags, reply headers, or a marketing category.
sensitive_templateThe send has "sensitive": false, but a sensitive template has the same key.
too_many_keysThe project has 1,000 keys, and this template_key is new.
invalid_requestcc, bcc, or attachments breaks a rule above. attr names the field.
invalid_headerA header in headers breaks a rule above.
invalid_tagA tag in tags breaks a rule above.
A field code, such as requiredAnother field is missing or breaks a rule above. attr names it.

When the test sender sends an email, PostHog ignores from and reply_to. The 202 response then has a warnings list with a sandbox_sender warning and a setup_url to verify your domain.

See retries and errors for the errors every send can get.

React Email

The Node.js SDK renders React Email components for you, from version 5.69.0:

Terminal
npm install posthog-node @react-email/render react react-dom

Pass the component as react, and the SDK renders the HTML and plain text:

JSX
await posthog.emails.send({
to: "ada@example.com",
templateKey: "order-shipped",
subject: "Your order shipped",
react: <OrderShippedEmail firstName="Ada" trackingUrl={trackingUrl} />,
distinctId: "user_123",
idempotencyKey: `order-shipped-${orderId}`,
})
  • Next.js: send from a route on the Node.js runtime. React Email doesn't render on the edge runtime.
  • Render it yourself: to keep a copy of the HTML, call render and toPlainText from @react-email/render, and pass html and text instead.

ErrorCause
invalid_formThe send has react and html, or react and templateId. Pass one.
missing_react_rendererInstall @react-email/render next to posthog-node.
react_render_failedThe component threw, or took longer than the request timeout, 15 seconds by default. error.cause has the component's error.

Test it

  • In your tests: each SDK page has a Write automated tests section, such as Node.js. It shows how to catch the request, so you can check what your code sends without sending anything.
  • For real: send to your own address, and open the send in the Log.

Next

Still have questions?

Was this page useful?