Send transactional emails with Rust

The Rust SDK 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. Until you verify your domain, emails go only to your team, from the test sender. To see an email in your inbox first, follow the quick start. New to sending from code? Read send emails from code.

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<SendEmailResult, EmailError>. 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

Terminal
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("<ph_project_token>".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<String, posthog::EmailError> {
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#"<p>Reset your password <a href="{reset_link}">here</a>. The link works for 1 hour.</p>"#
))
.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<SendEmailResult, EmailError>. 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. 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 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 for every field, and the quick start for the version each one needs.

Write automated tests

Start a local stub server with 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 on the Transactional tab.

Terminal
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("<p>Reset your password.</p>")
.idempotency_key("password-reset-1"),
)
.await
.unwrap();
assert_eq!(result.id, "msg_1");
send.assert_async().await;
}

Next

Still have questions?

Was this page useful?