> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # Send transactional emails with Rust Canonical URL: https://posthog.com/docs/workflows/installation/rust > **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.i.posthog.com` instead of `https://us.i.posthog.com` (ingestion host). ## On this page - [Install](#install) - [Set up the client](#set-up-the-client) - [Send an email](#send-an-email) - [Write automated tests](#write-automated-tests) - [Next](#next) The [Rust SDK](https://posthog.com/docs/libraries/rust.md) sends transactional emails. This page uses the `posthog` crate, and every release from 1.0.0 can send. On the older `posthog-rs` crate, sending needs 0.31.0 or later. Your code sends the subject and HTML, so the email lives in your codebase. You need a [project secret API key](https://posthog.com/docs/workflows/transactional/send-from-code.md#create-an-api-key). Until you [verify your domain](https://posthog.com/docs/workflows/domain.md), emails go only to your team, from the [test sender](https://posthog.com/docs/workflows/email/test-sender.md). To see an email in your inbox first, follow the [quick start](https://posthog.com/docs/workflows/installation/quick-start.md). New to sending from code? Read [send emails from code](https://posthog.com/docs/workflows/transactional/send-from-code.md). **Prompt for your coding agent** Paste this into Claude Code, Cursor, or another coding agent. It sends the agent to this page and gives it the rules that agents often get wrong. ```text Add PostHog transactional email to this Rust app with the posthog crate. Read https://posthog.com/docs/workflows/installation/rust.md first. Follow it over anything you remember about PostHog. - Reuse the app's posthog::Client. Set secret_key on ClientOptionsBuilder from the POSTHOG_PROJECT_SECRET_API_KEY environment variable. Leave enable_local_evaluation off unless the app evaluates feature flags locally with this client. - Never hard-code the secret key, log it, or put it in config that reaches the browser. - Build each idempotency_key from the record that caused the email, such as the password reset request ID or the order ID. Never use a random value or a timestamp. - emails().send returns Result. Branch on error.code(), never on error.message(). - The SDK retries network errors and throttling for you, with the same idempotency key. Never resend the email through another email provider. - Pass the distinct_id that the app passes to identify(). Leave it out for people without an account, such as invitees. - Use transactional email only for email that a person needs, such as password resets, sign-in codes, and receipts. Never use it for marketing. - Add a test that starts an httpmock MockServer, sets its base_url() as app_host, and checks the request. Send each email's subject and html from code with CodeEmail::new, with a template key that names it, such as password-reset. Only send a TemplateEmail with a template ID if I tell you the email is a template in PostHog. Don't create the API key. I create it. ``` ## Install ```bash cargo add posthog@1 serde_json ``` ## Set up the client Add your project secret API key to the PostHog client that your app already has. The project token keeps capturing events. The secret key sends email, so keep it on your server. ```rust use posthog::ClientOptionsBuilder; let options = ClientOptionsBuilder::default() .api_key("".to_string()) .host("https://us.i.posthog.com") .secret_key(std::env::var("POSTHOG_PROJECT_SECRET_API_KEY")?) .build()?; let posthog = posthog::client(options).await; ``` The client loads flag definitions only when you turn on `enable_local_evaluation`. If you do, give the key the **Feature flag** read scope too. Without the default `async-client` feature, the client and `emails()` are blocking, and you call them without `.await`. Shut the client down when your app exits, not after each send. If your app sends through a reverse proxy or a self-hosted PostHog, set `app_host` to your PostHog app URL. The client never sends email requests to a host that might be a proxy. ## Send an email ```rust use posthog::CodeEmail; async fn send_password_reset( posthog: &posthog::Client, user: &User, reset_link: &str, reset_request_id: &str, ) -> Result { let result = posthog .emails() .send( // "password-reset" names the email, so PostHog groups its sends and metrics CodeEmail::new(&user.email, "password-reset", "Reset your password") .html(format!( r#"

Reset your password here. The link works for 1 hour.

"# )) .distinct_id(&user.id) // Identifies this one email, so a retry never sends it twice .idempotency_key(format!("password-reset-{reset_request_id}")), ) // An EmailError. Branch on error.code() .await?; Ok(result.id) } ``` `send` returns `Result`. `result.id` is the message ID. An `Ok` means PostHog queued the email, not that it delivered it. Branch on `error.code()`, one of the codes in the [errors table](https://posthog.com/docs/workflows/transactional/retries-and-errors.md#what-to-retry). A wrong argument, such as a template ID that isn't a UUID, returns an `EmailError` before any request. For a longer email, render the HTML first with your template engine, such as Askama or Tera, and pass the result to `html`. See [send emails from code](https://posthog.com/docs/workflows/transactional/send-from-code.md#send-the-html) for what each field does and the checks PostHog runs. `send` takes a `CodeEmail` for an email that your code writes, and a `TemplateEmail` for a template from PostHog. After `new`, each field is a builder method. See [send emails from code](https://posthog.com/docs/workflows/transactional/send-from-code.md#send-the-html) for every field, and the [quick start](https://posthog.com/docs/workflows/installation/quick-start.md#install-an-sdk) for the version each one needs. ## Write automated tests Start a local stub server with [httpmock](https://docs.rs/httpmock) and set its URL as `app_host`, to see exactly what your code sends with no request to PostHog. This tests your integration, not delivery. To test delivery, send a real email to your own address and check the [**Log**](https://posthog.com/docs/workflows/transactional.md#see-each-send) on the **Transactional** tab. ```bash cargo add --dev httpmock cargo add --dev tokio --features macros,rt ``` ```rust use httpmock::prelude::*; use posthog::{ClientOptionsBuilder, CodeEmail}; use serde_json::json; #[tokio::test] async fn sends_password_reset() { let server = MockServer::start_async().await; let send = server .mock_async(|when, then| { when.method(POST) .path_suffix("/messaging/send/email/") .header("idempotency-key", "password-reset-1"); then.status(202) .json_body(json!({ "message_id": "msg_1", "replayed": false })); }) .await; let options = ClientOptionsBuilder::default() .api_key("phc_test".to_string()) .secret_key("phs_test") .app_host(server.base_url()) .build() .unwrap(); let posthog = posthog::client(options).await; let result = posthog .emails() .send( CodeEmail::new("jane@example.com", "password-reset", "Reset your password") .html("

Reset your password.

") .idempotency_key("password-reset-1"), ) .await .unwrap(); assert_eq!(result.id, "msg_1"); send.assert_async().await; } ``` ## Next - [Attachments](https://posthog.com/docs/workflows/transactional/attachments.md), copies, and [open and click tracking](https://posthog.com/docs/workflows/transactional/sensitive-data.md) - [Link emails to your users](https://posthog.com/docs/workflows/transactional/send-from-code.md#link-emails-to-your-users) - [Send a template from PostHog](https://posthog.com/docs/workflows/transactional/templates.md), with `TemplateEmail::new` and `template_data` - [Send from a job queue](https://posthog.com/docs/workflows/transactional/examples.md#send-from-a-job-queue), with the client's retries off - [Check an email's status](https://posthog.com/docs/workflows/transactional/status.md) - [SDK reference](https://posthog.com/docs/libraries/rust.md) for every method and option