> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # Send emails from code Canonical URL: https://posthog.com/docs/workflows/transactional/send-from-code > **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.posthog.com` instead of `https://us.posthog.com` or `https://app.posthog.com` (app host for links). ## On this page - [How a send works](#how-a-send-works) - [Create an API key](#create-an-api-key) - [Send the HTML](#send-the-html) - [See it in PostHog](#see-it-in-posthog) - [Link emails to your users](#link-emails-to-your-users) - [Email engagement events](#email-engagement-events) - [Rules transactional emails follow](#rules-transactional-emails-follow) - [Checks](#checks) - [React Email](#react-email) - [Test it](#test-it) - [Next](#next) 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](https://posthog.com/docs/workflows/installation/quick-start.md#install-an-sdk). ## How a send works 1. **Your server calls PostHog** with a project secret API key, through an [SDK](https://posthog.com/docs/workflows/installation/quick-start.md) or the [API](https://posthog.com/docs/workflows/installation/api.md). 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](https://posthog.com/docs/workflows/broadcasts/large-audiences.md#your-sending-allowance), but it counts toward it. 5. **The status moves on:** sent, then delivered, bounced, or complained. You can [check it](https://posthog.com/docs/workflows/transactional/status.md) for 30 days. 6. **Events land on the person:** sent, delivered, opened, clicked, and so on, if [engagement events](#email-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](https://posthog.com/docs/workflows/concepts/reliable-delivery.md). ## Create an API key Send with a [project secret API key](https://posthog.com/docs/api/project-secret-api-keys.md) that has the **Transactional email** scope. 1. Go to [**Project secret API keys**](https://app.posthog.com/settings/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](https://res.cloudinary.com/dmukukwp6/image/upload/w_1600,c_limit,q_auto,f_auto/create_project_secret_key_light_5829ffc608.png) 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: ### Node.js ```javascript 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", }) ``` ### Python ```python result = posthog.emails.send( to="ada@example.com", template_key="password-reset", subject="Reset your password", html=html, distinct_id="user_123", idempotency_key="password-reset-8f14e45f", ) ``` ### Ruby ```ruby result = $posthog.emails.send( to: 'ada@example.com', template_key: 'password-reset', subject: 'Reset your password', html: html, distinct_id: 'user_123', idempotency_key: 'password-reset-8f14e45f' ) ``` ### Rust ```rust let result = posthog .emails() .send( CodeEmail::new("ada@example.com", "password-reset", "Reset your password") .html(html) .distinct_id("user_123") .idempotency_key("password-reset-8f14e45f"), ) .await?; ``` ### PHP ```php $result = PostHog::emails()->send([ 'to' => 'ada@example.com', 'template_key' => 'password-reset', 'subject' => 'Reset your password', 'html' => $html, 'distinct_id' => 'user_123', 'idempotency_key' => 'password-reset-8f14e45f', ]); ``` ### Go ```go result, err := client.Emails().Send(ctx, posthog.CodeEmail{ To: "ada@example.com", TemplateKey: "password-reset", Subject: "Reset your password", HTML: html, DistinctID: "user_123", IdempotencyKey: "password-reset-8f14e45f", }) ``` ### .NET ```csharp var result = await emails.SendAsync(new SendCodeEmailOptions { To = "ada@example.com", TemplateKey = "password-reset", Subject = "Reset your password", Html = html, DistinctId = "user_123", IdempotencyKey = "password-reset-8f14e45f", }); ``` ### Elixir ```elixir {:ok, result} = PostHog.Emails.send( to: "ada@example.com", template_key: "password-reset", subject: "Reset your password", html: html, distinct_id: "user_123", idempotency_key: "password-reset-8f14e45f" ) ``` ### REST ```bash curl -X POST "https://us.posthog.com/api/messaging/send/email/" \ -H "Authorization: Bearer $POSTHOG_PROJECT_SECRET_API_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: password-reset-8f14e45f" \ -d '{"template_key": "password-reset", "to": "ada@example.com", "distinct_id": "user_123", "subject": "Reset your password", "html": "

Reset it here.

"}' ``` | Field | Required | What it does | | --- | --- | --- | | `template_key` | Yes | Names 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. | | `to` | Yes | The recipient. | | `subject` | Yes | The subject. | | `html` or `text` | One of them | The body, up to 5 MiB each. PostHog sends it as written. Leave out `text` and PostHog makes it from `html`. | | `distinct_id` | No | The user's distinct ID, so the send lands on their person. | | `from` | No | Such as `Hedgebox `, on a verified domain. Defaults to the project's default sender, or its only verified sender. | | `reply_to` | No | Up to 10 addresses. | | `cc` | No | Up to 10 addresses that get a copy. Plain addresses only, with no names. | | `bcc` | No | Up to 10 addresses that get a hidden copy. Plain addresses only, with no names. | | `attachments` | No | Files to attach. See [attachments](https://posthog.com/docs/workflows/transactional/attachments.md). | | `sensitive` | No | See [sensitive data and tracking](https://posthog.com/docs/workflows/transactional/sensitive-data.md). | | `tracking` | No | Turn opens, clicks, and engagement events on or off. | | `headers` | No | Up to 8 email headers to add, such as `{"X-Entity-Ref-ID": "order-1234"}`. See [headers and tags](#headers-and-tags). | | `tags` | No | Up to 10 names and values, such as `{"plan": "pro"}`, to break down the email's events by. See [headers and tags](#headers-and-tags). | | `Idempotency-Key` header | No | Send one so a retry never sends the email twice. Send it as a header, not in the body. See [retries and errors](https://posthog.com/docs/workflows/transactional/retries-and-errors.md). | 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](https://posthog.com/docs/workflows/transactional/templates.md) instead, and send its template ID. Both get the same checks, statuses, events, and metrics. Ask your agentwith the [PostHog MCP](https://posthog.com/docs/workflows/mcp.md)[sending-transactional-emails](https://posthog.com/docs/workflows/skills.md) “Move our transactional emails to send through PostHog, keeping the HTML in our code.” Copy ### 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](#email-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](https://res.cloudinary.com/dmukukwp6/image/upload/w_1600,c_limit,q_auto,f_auto/code_email_page_light_1490fca88c.png) Ask your agentwith the [PostHog MCP](https://posthog.com/docs/workflows/mcp.md)[measuring-email-performance](https://posthog.com/docs/workflows/skills.md) “How did our password-reset email do last week, and how many people finished resetting their password?” Copy ## Link emails to your users 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](https://posthog.com/docs/workflows/transactional.md#see-each-send) 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](https://posthog.com/docs/workflows/email/engagement-events.md), 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](https://posthog.com/docs/workflows/transactional/sensitive-data.md) email's events leave out the subject. Use the events in [funnels](https://posthog.com/docs/product-analytics/funnels.md) and [insights](https://posthog.com/docs/product-analytics/insights.md), 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](https://posthog.com/docs/workflows/metrics.md). ## Rules transactional emails follow - **No opt-outs or frequency cap.** Only the [suppression list](https://posthog.com/docs/workflows/email/suppression.md) 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](https://posthog.com/docs/workflows/concepts/marketing-vs-transactional.md). - **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](https://posthog.com/docs/workflows/reference/limits.md#api-and-sdk-limits), and how to [handle a rate limit](https://posthog.com/docs/workflows/transactional/retries-and-errors.md#rate-limits). - **Billing.** Billed like other emails. See [pricing](https://posthog.com/pricing.md). ## Checks PostHog sends nothing when one of these checks fails. Each returns `400`. | Code | Cause | | --- | --- | | `sender_not_verified` | The project has no verified sender, no verified sender can send from `from`, or the default sender isn't verified. | | `sender_required` | There'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_unsupported` | The project has no verified domain, so the [test sender](https://posthog.com/docs/workflows/email/test-sender.md) sends the email, and the send has `cc`, `bcc`, `attachments`, `headers`, `tags`, reply headers, or a marketing `category`. | | `sensitive_template` | The send has `"sensitive": false`, but a sensitive template has the same key. | | `too_many_keys` | The project has 1,000 keys, and this `template_key` is new. | | `invalid_request` | `cc`, `bcc`, or `attachments` breaks a rule above. `attr` names the field. | | `invalid_header` | A header in `headers` breaks a rule above. | | `invalid_tag` | A tag in `tags` breaks a rule above. | | A field code, such as `required` | Another 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](https://posthog.com/docs/workflows/domain.md). See [retries and errors](https://posthog.com/docs/workflows/transactional/retries-and-errors.md) for the errors every send can get. ## React Email The Node.js SDK renders React Email components for you, from version 5.69.0: ```bash 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: , 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. | Error | Cause | | --- | --- | | `invalid_form` | The send has `react` and `html`, or `react` and `templateId`. Pass one. | | `missing_react_renderer` | Install `@react-email/render` next to `posthog-node`. | | `react_render_failed` | The 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](https://posthog.com/docs/workflows/installation/node.md#write-automated-tests). 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](https://posthog.com/docs/workflows/transactional.md#see-each-send). ## Next - [Templates in PostHog](https://posthog.com/docs/workflows/transactional/templates.md) - [Retries and errors](https://posthog.com/docs/workflows/transactional/retries-and-errors.md) - [Examples](https://posthog.com/docs/workflows/transactional/examples.md): sign-in codes, invites, and receipts with a PDF.