> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt # Examples Canonical URL: https://posthog.com/docs/workflows/transactional/examples > **Cloud region:** This page uses US Cloud hosts. For an EU Cloud project, use `https://eu.posthog.com` instead of `https://us.posthog.com` (app host for links). ## On this page - [Sign-in code](#sign-in-code) - [Email address check](#email-address-check) - [Team invite](#team-invite) - [Receipt with a PDF](#receipt-with-a-pdf) - [Send from a job queue](#send-from-a-job-queue) - [Measure whether an email works](#measure-whether-an-email-works) 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](https://posthog.com/docs/workflows/installation/quick-start.md), and [created the email](https://posthog.com/docs/workflows/transactional/templates.md) with the variables that the example sends. ## Sign-in code Send a one-time code when someone signs in without a password. | Setting | Value | | --- | --- | | Template variables | `code`, `expires_in_minutes` | | [Protect sensitive data](https://posthog.com/docs/workflows/transactional/sensitive-data.md) | On, so PostHog keeps no copy of the code | | Distinct ID | The user's ID | | Idempotency key | `sign-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. ``` ### Node.js ```javascript const { error } = await posthog.emails.send({ to: user.email, templateId: "", templateData: { code: signInCode.code, expires_in_minutes: 10 }, distinctId: user.id, idempotencyKey: `sign-in-code-${signInCode.id}`, }) if (error) { throw error } ``` ### Python ```python posthog.emails.send( to=user.email, template_id="", template_data={"code": sign_in_code.code, "expires_in_minutes": 10}, distinct_id=str(user.id), idempotency_key=f"sign-in-code-{sign_in_code.id}", ) ``` ### Ruby ```ruby $posthog.emails.send( to: user.email, template_id: '', template_data: { code: sign_in_code.code, expires_in_minutes: 10 }, distinct_id: user.id.to_s, idempotency_key: "sign-in-code-#{sign_in_code.id}" ) ``` ### Rust ```rust posthog .emails() .send( TemplateEmail::new(&user.email, "") .template_data(json!({ "code": sign_in_code.code, "expires_in_minutes": 10 })) .distinct_id(&user.id) .idempotency_key(format!("sign-in-code-{}", sign_in_code.id)), ) .await?; ``` ### PHP ```php PostHog::emails()->send([ 'to' => $user->email, 'template_id' => '', 'template_data' => ['code' => $signInCode->code, 'expires_in_minutes' => 10], 'distinct_id' => (string) $user->id, 'idempotency_key' => "sign-in-code-{$signInCode->id}", ]); ``` ### Go ```go _, err := client.Emails().Send(ctx, posthog.TemplateEmail{ To: user.Email, TemplateID: "", TemplateData: map[string]interface{}{"code": signInCode.Code, "expires_in_minutes": 10}, DistinctID: user.ID, IdempotencyKey: "sign-in-code-" + signInCode.ID, }) if err != nil { return err } ``` ### .NET ```csharp await emails.SendAsync(new SendTemplateEmailOptions { To = user.Email, TemplateId = Guid.Parse(""), TemplateData = new Dictionary { ["code"] = signInCode.Code, ["expires_in_minutes"] = 10, }, DistinctId = user.Id, IdempotencyKey = $"sign-in-code-{signInCode.Id}", }); ``` ### Elixir ```elixir {:ok, _result} = PostHog.Emails.send( to: user.email, template_id: "", template_data: %{code: sign_in_code.code, expires_in_minutes: 10}, distinct_id: to_string(user.id), idempotency_key: "sign-in-code-#{sign_in_code.id}" ) ``` ### 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: sign-in-code-8f14e45f" \ -d '{"template_id": "", "to": "ada@example.com", "distinct_id": "user_123", "message_data": {"code": "482913", "expires_in_minutes": 10}}' ``` 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. | Setting | Value | | --- | --- | | Template variables | `first_name`, `verify_link` | | Protect sensitive data | On, so the link's token never goes through a tracking redirect | | Distinct ID | The new user's ID. Call `identify()` with the same ID when the user signs up. | | Idempotency key | `verify-email-{verification_id}` | ### Node.js ```javascript const { error } = await posthog.emails.send({ to: user.email, templateId: "", 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 } ``` ### Python ```python posthog.emails.send( to=user.email, template_id="", template_data={ "first_name": user.first_name, "verify_link": f"https://example.com/verify?token={verification.token}", }, distinct_id=str(user.id), idempotency_key=f"verify-email-{verification.id}", ) ``` ### Ruby ```ruby $posthog.emails.send( to: user.email, template_id: '', template_data: { first_name: user.first_name, verify_link: "https://example.com/verify?token=#{verification.token}" }, distinct_id: user.id.to_s, idempotency_key: "verify-email-#{verification.id}" ) ``` ### Rust ```rust posthog .emails() .send( TemplateEmail::new(&user.email, "") .template_data(json!({ "first_name": user.first_name, "verify_link": format!("https://example.com/verify?token={}", verification.token), })) .distinct_id(&user.id) .idempotency_key(format!("verify-email-{}", verification.id)), ) .await?; ``` ### PHP ```php PostHog::emails()->send([ 'to' => $user->email, 'template_id' => '', 'template_data' => [ 'first_name' => $user->firstName, 'verify_link' => "https://example.com/verify?token={$verification->token}", ], 'distinct_id' => (string) $user->id, 'idempotency_key' => "verify-email-{$verification->id}", ]); ``` ### Go ```go _, err := client.Emails().Send(ctx, posthog.TemplateEmail{ To: user.Email, TemplateID: "", TemplateData: map[string]interface{}{ "first_name": user.FirstName, "verify_link": "https://example.com/verify?token=" + verification.Token, }, DistinctID: user.ID, IdempotencyKey: "verify-email-" + verification.ID, }) if err != nil { return err } ``` ### .NET ```csharp await emails.SendAsync(new SendTemplateEmailOptions { To = user.Email, TemplateId = Guid.Parse(""), TemplateData = new Dictionary { ["first_name"] = user.FirstName, ["verify_link"] = $"https://example.com/verify?token={verification.Token}", }, DistinctId = user.Id, IdempotencyKey = $"verify-email-{verification.Id}", }); ``` ### Elixir ```elixir {:ok, _result} = PostHog.Emails.send( to: user.email, template_id: "", template_data: %{ first_name: user.first_name, verify_link: "https://example.com/verify?token=#{verification.token}" }, distinct_id: to_string(user.id), idempotency_key: "verify-email-#{verification.id}" ) ``` ### 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: verify-email-c9f0f895" \ -d '{"template_id": "", "to": "ada@example.com", "distinct_id": "user_123", "message_data": {"first_name": "Ada", "verify_link": "https://example.com/verify?token=abc"}}' ``` Send it from a background job after you save the user, so a slow send never holds up the sign-up. Your [SDK page](https://posthog.com/docs/workflows/installation/quick-start.md) 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. Ask your agentwith the [PostHog MCP](https://posthog.com/docs/workflows/mcp.md)[sending-transactional-emails](https://posthog.com/docs/workflows/skills.md) “Add a team invite email to our app that sends through PostHog.” Copy | Setting | Value | | --- | --- | | Template variables | `inviter_name`, `team_name`, `accept_link` | | Protect sensitive data | On, because the link carries the invite token | | Distinct ID | Leave it out. The invitee isn't a user yet, so you have no distinct ID for them. | | Idempotency key | `invite-{invite_id}` | ### Node.js ```javascript const { error } = await posthog.emails.send({ to: invite.email, templateId: "", 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 } ``` ### Python ```python posthog.emails.send( to=invite.email, template_id="", template_data={ "inviter_name": inviter.name, "team_name": team.name, "accept_link": f"https://example.com/invites/{invite.token}", }, idempotency_key=f"invite-{invite.id}", ) ``` ### Ruby ```ruby $posthog.emails.send( to: invite.email, template_id: '', template_data: { inviter_name: inviter.name, team_name: team.name, accept_link: "https://example.com/invites/#{invite.token}" }, idempotency_key: "invite-#{invite.id}" ) ``` ### Rust ```rust posthog .emails() .send( TemplateEmail::new(&invite.email, "") .template_data(json!({ "inviter_name": inviter.name, "team_name": team.name, "accept_link": format!("https://example.com/invites/{}", invite.token), })) .idempotency_key(format!("invite-{}", invite.id)), ) .await?; ``` ### PHP ```php PostHog::emails()->send([ 'to' => $invite->email, 'template_id' => '', 'template_data' => [ 'inviter_name' => $inviter->name, 'team_name' => $team->name, 'accept_link' => "https://example.com/invites/{$invite->token}", ], 'idempotency_key' => "invite-{$invite->id}", ]); ``` ### Go ```go _, err := client.Emails().Send(ctx, posthog.TemplateEmail{ To: invite.Email, TemplateID: "", TemplateData: map[string]interface{}{ "inviter_name": inviter.Name, "team_name": team.Name, "accept_link": "https://example.com/invites/" + invite.Token, }, IdempotencyKey: "invite-" + invite.ID, }) if err != nil { return err } ``` ### .NET ```csharp await emails.SendAsync(new SendTemplateEmailOptions { To = invite.Email, TemplateId = Guid.Parse(""), TemplateData = new Dictionary { ["inviter_name"] = inviter.Name, ["team_name"] = team.Name, ["accept_link"] = $"https://example.com/invites/{invite.Token}", }, IdempotencyKey = $"invite-{invite.Id}", }); ``` ### Elixir ```elixir {:ok, _result} = PostHog.Emails.send( to: invite.email, template_id: "", template_data: %{ inviter_name: inviter.name, team_name: team.name, accept_link: "https://example.com/invites/#{invite.token}" }, idempotency_key: "invite-#{invite.id}" ) ``` ### 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: invite-45c48cce" \ -d '{"template_id": "", "to": "grace@example.com", "message_data": {"inviter_name": "Ada", "team_name": "Hedgebox", "accept_link": "https://example.com/invites/abc"}}' ``` 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](https://posthog.com/docs/workflows/transactional/send-from-code.md#send-the-html), so your code renders the email. | Setting | Value | | --- | --- | | Template key | `receipt` | | Copies | `cc` to the customer's billing contact | | Attachment | The invoice PDF. See the [limits](https://posthog.com/docs/workflows/transactional/attachments.md#attach-files). | | Distinct ID | The customer's user ID | | Idempotency key | `receipt-{order_id}` | ### Node.js ```javascript 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 } ``` ### Python ```python from pathlib import Path posthog.emails.send( to=order.customer.email, template_key="receipt", subject=f"Your receipt for order {order.number}", html=html, cc=order.customer.billing_email, attachments=[ { "filename": f"invoice-{order.number}.pdf", "content": Path(invoice_path).read_bytes(), "content_type": "application/pdf", } ], distinct_id=str(order.customer.user_id), idempotency_key=f"receipt-{order.id}", ) ``` ### Ruby ```ruby $posthog.emails.send( to: order.customer.email, template_key: 'receipt', subject: "Your receipt for order #{order.number}", html: html, cc: order.customer.billing_email, attachments: [ { filename: "invoice-#{order.number}.pdf", content: File.binread(invoice_path), content_type: 'application/pdf' } ], distinct_id: order.customer.user_id.to_s, idempotency_key: "receipt-#{order.id}" ) ``` ### Rust ```rust let invoice_pdf = std::fs::read(invoice_path)?; posthog .emails() .send( CodeEmail::new(&order.customer.email, "receipt", format!("Your receipt for order {}", order.number)) .html(html) .cc(&order.customer.billing_email) .attachment( EmailAttachment::new(format!("invoice-{}.pdf", order.number), invoice_pdf) .content_type("application/pdf"), ) .distinct_id(&order.customer.user_id) .idempotency_key(format!("receipt-{}", order.id)), ) .await?; ``` ### PHP ```php PostHog::emails()->send([ 'to' => $order->customer->email, 'template_key' => 'receipt', 'subject' => "Your receipt for order {$order->number}", 'html' => $html, 'cc' => $order->customer->billingEmail, 'attachments' => [ ['filename' => "invoice-{$order->number}.pdf", 'content' => file_get_contents($invoicePath), 'content_type' => 'application/pdf'], ], 'distinct_id' => (string) $order->customer->userId, 'idempotency_key' => "receipt-{$order->id}", ]); ``` ### Go ```go invoicePDF, err := os.ReadFile(invoicePath) if err != nil { return err } _, err = client.Emails().Send(ctx, posthog.CodeEmail{ To: order.Customer.Email, TemplateKey: "receipt", Subject: "Your receipt for order " + order.Number, HTML: html, Cc: []string{order.Customer.BillingEmail}, Attachments: []posthog.EmailAttachment{ {Filename: "invoice-" + order.Number + ".pdf", Content: invoicePDF, ContentType: "application/pdf"}, }, DistinctID: order.Customer.UserID, IdempotencyKey: "receipt-" + order.ID, }) if err != nil { return err } ``` ### .NET ```csharp await emails.SendAsync(new SendCodeEmailOptions { To = order.Customer.Email, TemplateKey = "receipt", Subject = $"Your receipt for order {order.Number}", Html = html, Cc = [order.Customer.BillingEmail], Attachments = [ new EmailAttachment { Filename = $"invoice-{order.Number}.pdf", Content = await File.ReadAllBytesAsync(invoicePath), ContentType = "application/pdf", }, ], DistinctId = order.Customer.UserId, IdempotencyKey = $"receipt-{order.Id}", }); ``` ### Elixir ```elixir {:ok, _result} = PostHog.Emails.send( to: order.customer.email, template_key: "receipt", subject: "Your receipt for order #{order.number}", html: html, cc: order.customer.billing_email, attachments: [ %{ filename: "invoice-#{order.number}.pdf", content: File.read!(invoice_path), content_type: "application/pdf" } ], distinct_id: to_string(order.customer.user_id), idempotency_key: "receipt-#{order.id}" ) ``` ### REST ```bash #!/usr/bin/env bash set -euo pipefail FILE="invoice-1042.pdf" SHA256=$(shasum -a 256 "$FILE" | cut -d " " -f 1) SIZE=$(wc -c < "$FILE" | tr -d " ") # 1. Ask where to upload the file ANSWER=$(curl -sS --fail-with-body -X POST "https://us.posthog.com/api/messaging/attachments/uploads/" \ -H "Authorization: Bearer $POSTHOG_PROJECT_SECRET_API_KEY" \ -H "Content-Type: application/json" \ -d "{\"files\": [{\"sha256\": \"$SHA256\", \"size\": $SIZE}]}") || { echo "$ANSWER" >&2; exit 1; } SLOT=$(jq ".files[0]" <<< "$ANSWER") # 2. Upload the file, if PostHog doesn't have it yet if [ "$(jq -r .status <<< "$SLOT")" = "upload" ]; then HEADERS=() while IFS= read -r HEADER; do HEADERS+=(-H "$HEADER") done < <(jq -r '.headers | to_entries[] | "\(.key): \(.value)"' <<< "$SLOT") curl -sS --fail-with-body -X PUT "$(jq -r .url <<< "$SLOT")" "${HEADERS[@]}" --data-binary "@$FILE" fi # 3. Send the email with the file curl -sS --fail-with-body -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: receipt-ord_1042" \ -d '{ "template_key": "receipt", "to": "ada@example.com", "cc": ["billing@example.com"], "subject": "Your receipt for order 1042", "html": "

Thanks for your order. Your invoice is attached.

", "distinct_id": "user_123", "attachments": [ {"sha256": "'"$SHA256"'", "filename": "invoice-1042.pdf", "content_type": "application/pdf"} ] }' ``` 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`](https://jqlang.org). On Linux without `shasum`, use `sha256sum "$FILE"` in its place. See [send files with the API](https://posthog.com/docs/workflows/transactional/attachments.md#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. ### Node.js ```javascript 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: `

Reset your password here.

`, 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 } } ) ``` ### Python ```python from celery import shared_task from posthog.emails import EmailError # A later attempt can fix these. Any other code fails the same way again. RETRYABLE_CODES = {"network_error", "idempotency_key_in_flight", "throttled", "delivery_unavailable"} @shared_task(bind=True, max_retries=5) def send_password_reset_email(self, user_id: str, email: str, reset_link: str, reset_request_id: str) -> str: try: result = posthog.emails.send( to=email, template_key="password-reset", subject="Reset your password", html=f'

Reset your password here.

', distinct_id=user_id, # The same key on every attempt, so a retried task never sends the email twice idempotency_key=f"password-reset-{reset_request_id}", # Celery retries the task, so the client doesn't retry on its own max_retries=0, ) except EmailError as error: if error.code in RETRYABLE_CODES: # Waits 10, 20, 40, 80, then 160 seconds raise self.retry(exc=error, countdown=10 * 2**self.request.retries) # Any other code marks the task as failed, with no retry raise return result.id ``` ### Ruby ```ruby class PasswordResetEmailJob include Sidekiq::Job # Five retries with Sidekiq's backoff finish within minutes, well inside the 7 days sidekiq_options retry: 5 # A later attempt can fix these. Any other code fails the same way again. RETRYABLE_CODES = %w[network_error idempotency_key_in_flight throttled delivery_unavailable].freeze sidekiq_retry_in do |_count, error| retryable = error.is_a?(PostHog::EmailError) && RETRYABLE_CODES.include?(error.code) retryable ? nil : :kill end def perform(user_id, email, reset_link, reset_request_id) $posthog.emails.send( to: email, template_key: 'password-reset', subject: 'Reset your password', html: %(

Reset your password here.

), distinct_id: user_id, # The same key on every attempt, so a retried job never sends the email twice idempotency_key: "password-reset-#{reset_request_id}", # Sidekiq retries the job, so the client doesn't retry on its own max_retries: 0 ) end end ``` ### Rust ```rust use posthog::{CodeEmail, EmailError}; // A later attempt can fix these. Any other code fails the same way again. const RETRYABLE_CODES: [&str; 4] = ["network_error", "idempotency_key_in_flight", "throttled", "delivery_unavailable"]; pub enum JobError { // Run the job again later, with the same arguments Retry(EmailError), // Fail the job for good Permanent(EmailError), } pub struct PasswordResetJob { pub user_id: String, pub email: String, pub reset_link: String, pub reset_request_id: String, } pub async fn run_password_reset_job( posthog: &posthog::Client, job: &PasswordResetJob, ) -> Result { let email = CodeEmail::new(&job.email, "password-reset", "Reset your password") .html(format!(r#"

Reset your password here.

"#, job.reset_link)) .distinct_id(&job.user_id) // The same key on every attempt, so a retried job never sends the email twice .idempotency_key(format!("password-reset-{}", job.reset_request_id)) // The queue retries the job, so the client doesn't retry on its own .max_retries(0); match posthog.emails().send(email).await { Ok(result) => Ok(result.id), Err(error) if RETRYABLE_CODES.contains(&error.code()) => Err(JobError::Retry(error)), Err(error) => Err(JobError::Permanent(error)), } } ``` ### PHP ```php namespace App\Jobs; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Queue\Queueable; use PostHog\EmailError; use PostHog\PostHog; class SendPasswordResetEmail implements ShouldQueue { use Queueable; // A later attempt can fix these. Any other code fails the same way again. private const RETRYABLE_CODES = ['network_error', 'idempotency_key_in_flight', 'throttled', 'delivery_unavailable']; public $tries = 5; public $backoff = [10, 60, 300]; public function __construct( public string $userId, public string $email, public string $resetLink, public string $resetRequestId, ) {} public function handle(): void { try { PostHog::emails()->send([ 'to' => $this->email, 'template_key' => 'password-reset', 'subject' => 'Reset your password', 'html' => "

Reset your password resetLink}\">here.

", 'distinct_id' => $this->userId, // The same key on every attempt, so a retried job never sends the email twice 'idempotency_key' => "password-reset-{$this->resetRequestId}", // Laravel retries the job, so the client doesn't retry on its own 'max_retries' => 0, ]); } catch (EmailError $error) { if (in_array($error->getErrorCode(), self::RETRYABLE_CODES, true)) { throw $error; } $this->fail($error); } } } // Dispatch the job with the values that the send needs: SendPasswordResetEmail::dispatch((string) $user->id, $user->email, $resetLink, $resetRequestId); ``` ### Go ```go import ( "context" "errors" "slices" "github.com/posthog/posthog-go/v2" "github.com/riverqueue/river" ) // A later attempt can fix these. Any other code fails the same way again. var retryableCodes = []string{"network_error", "idempotency_key_in_flight", "throttled", "delivery_unavailable"} type PasswordResetArgs struct { UserID string `json:"user_id"` Email string `json:"email"` ResetLink string `json:"reset_link"` ResetRequestID string `json:"reset_request_id"` } func (PasswordResetArgs) Kind() string { return "password_reset_email" } // Five attempts finish within minutes, well inside the 7 days that PostHog keeps an idempotency key func (PasswordResetArgs) InsertOpts() river.InsertOpts { return river.InsertOpts{MaxAttempts: 5} } type PasswordResetWorker struct { river.WorkerDefaults[PasswordResetArgs] PostHog posthog.Client } func (w *PasswordResetWorker) Work(ctx context.Context, job *river.Job[PasswordResetArgs]) error { args := job.Args _, err := w.PostHog.Emails().Send(ctx, posthog.CodeEmail{ To: args.Email, TemplateKey: "password-reset", Subject: "Reset your password", HTML: `

Reset your password here.

`, DistinctID: args.UserID, // The same key on every attempt, so a retried job never sends the email twice IdempotencyKey: "password-reset-" + args.ResetRequestID, // River retries the job, so the client doesn't retry on its own MaxRetries: posthog.Ptr(0), }) var emailErr *posthog.EmailError if errors.As(err, &emailErr) && !slices.Contains(retryableCodes, emailErr.Code) { // River doesn't run a cancelled job again return river.JobCancel(err) } return err } // Register the worker with river.AddWorker(workers, &PasswordResetWorker{PostHog: client}). ``` ### .NET ```csharp using Hangfire; using PostHog.Emails; public class PasswordResetEmailJob(IPostHogEmails emails) { // A later attempt can fix these. Any other code fails the same way again. static readonly HashSet RetryableCodes = ["network_error", "idempotency_key_in_flight", "throttled", "delivery_unavailable"]; [AutomaticRetry( Attempts = 5, DelaysInSeconds = new[] { 10, 60, 300 }, ExceptOn = new[] { typeof(PermanentEmailFailure), typeof(ArgumentException) })] public async Task SendAsync(string userId, string email, string resetLink, string resetRequestId) { try { await emails.SendAsync(new SendCodeEmailOptions { To = email, TemplateKey = "password-reset", Subject = "Reset your password", Html = $"

Reset your password here.

", DistinctId = userId, // The same key on every attempt, so a retried job never sends the email twice IdempotencyKey = $"password-reset-{resetRequestId}", // Hangfire retries the job, so the client doesn't retry on its own MaxRetries = 0, }); } catch (EmailException error) when (!RetryableCodes.Contains(error.Code)) { throw new PermanentEmailFailure(error); } } } public class PermanentEmailFailure(EmailException error) : Exception($"{error.Code}: {error.Message}", error); // Queue the job with the same values that the send needs: BackgroundJob.Enqueue(job => job.SendAsync(user.Id, user.Email, resetLink, resetRequestId)); ``` ### Elixir ```elixir defmodule MyApp.Workers.PasswordResetEmail do use Oban.Worker, queue: :emails, max_attempts: 10 # A later attempt can fix these. Any other code fails the same way again. @retryable_codes ["network_error", "idempotency_key_in_flight", "throttled", "delivery_unavailable"] @impl Oban.Worker def perform(%Oban.Job{args: args}) do # Oban stores args as JSON, so the keys are strings %{ "user_id" => user_id, "email" => email, "reset_link" => reset_link, "reset_request_id" => reset_request_id } = args case PostHog.Emails.send( to: email, template_key: "password-reset", subject: "Reset your password", html: ~s(

Reset your password here.

), distinct_id: to_string(user_id), # The same key on every attempt, so a retried job never sends the email twice idempotency_key: "password-reset-#{reset_request_id}", # Oban retries the job, so the SDK doesn't retry on its own max_retries: 0 ) do {:ok, _result} -> :ok {:error, %PostHog.Emails.Error{code: code} = error} when code in @retryable_codes -> {:error, error} {:error, error} -> {:cancel, error} end end end # Add the job where your app creates the reset request: %{ user_id: user.id, email: user.email, reset_link: reset_link, reset_request_id: reset_request.id } |> MyApp.Workers.PasswordResetEmail.new() |> Oban.insert() ``` ## 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](https://posthog.com/docs/workflows/email/engagement-events.md) for your project. For example, to see how many people finish a password reset after they get the email, build a [funnel](https://posthog.com/docs/product-analytics/funnels.md) 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.