Examples
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, and created the email 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 | 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 |
Your sign-in code is {{ variables.code }}. It expires in {{ variables.expires_in_minutes }} minutes.
const { error } = await posthog.emails.send({to: user.email,templateId: "<template_id>",templateData: { code: signInCode.code, expires_in_minutes: 10 },distinctId: user.id,idempotencyKey: `sign-in-code-${signInCode.id}`,})if (error) {throw error}
posthog.emails.send(to=user.email,template_id="<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}",)
$posthog.emails.send(to: user.email,template_id: '<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}")
posthog.emails().send(TemplateEmail::new(&user.email, "<template_id>").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?;
PostHog::emails()->send(['to' => $user->email,'template_id' => '<template_id>','template_data' => ['code' => $signInCode->code, 'expires_in_minutes' => 10],'distinct_id' => (string) $user->id,'idempotency_key' => "sign-in-code-{$signInCode->id}",]);
_, err := client.Emails().Send(ctx, posthog.TemplateEmail{To: user.Email,TemplateID: "<template_id>",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}
await emails.SendAsync(new SendTemplateEmailOptions{To = user.Email,TemplateId = Guid.Parse("<template_id>"),TemplateData = new Dictionary<string, object>{["code"] = signInCode.Code,["expires_in_minutes"] = 10,},DistinctId = user.Id,IdempotencyKey = $"sign-in-code-{signInCode.Id}",});
{:ok, _result} =PostHog.Emails.send(to: user.email,template_id: "<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}")
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": "<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} |
const { error } = await posthog.emails.send({to: user.email,templateId: "<template_id>",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}
posthog.emails.send(to=user.email,template_id="<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}",)
$posthog.emails.send(to: user.email,template_id: '<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}")
posthog.emails().send(TemplateEmail::new(&user.email, "<template_id>").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?;
PostHog::emails()->send(['to' => $user->email,'template_id' => '<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}",]);
_, err := client.Emails().Send(ctx, posthog.TemplateEmail{To: user.Email,TemplateID: "<template_id>",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}
await emails.SendAsync(new SendTemplateEmailOptions{To = user.Email,TemplateId = Guid.Parse("<template_id>"),TemplateData = new Dictionary<string, object>{["first_name"] = user.FirstName,["verify_link"] = $"https://example.com/verify?token={verification.Token}",},DistinctId = user.Id,IdempotencyKey = $"verify-email-{verification.Id}",});
{:ok, _result} =PostHog.Emails.send(to: user.email,template_id: "<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}")
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": "<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 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.
| 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} |
const { error } = await posthog.emails.send({to: invite.email,templateId: "<template_id>",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}
posthog.emails.send(to=invite.email,template_id="<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}",)
$posthog.emails.send(to: invite.email,template_id: '<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}")
posthog.emails().send(TemplateEmail::new(&invite.email, "<template_id>").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?;
PostHog::emails()->send(['to' => $invite->email,'template_id' => '<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}",]);
_, err := client.Emails().Send(ctx, posthog.TemplateEmail{To: invite.Email,TemplateID: "<template_id>",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}
await emails.SendAsync(new SendTemplateEmailOptions{To = invite.Email,TemplateId = Guid.Parse("<template_id>"),TemplateData = new Dictionary<string, object>{["inviter_name"] = inviter.Name,["team_name"] = team.Name,["accept_link"] = $"https://example.com/invites/{invite.Token}",},IdempotencyKey = $"invite-{invite.Id}",});
{:ok, _result} =PostHog.Emails.send(to: invite.email,template_id: "<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}")
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": "<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, 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. |
| Distinct ID | The customer's user ID |
| Idempotency key | receipt-{order_id} |
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}
from pathlib import Pathposthog.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}",)
$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}")
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?;
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}",]);
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}
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}",});
{: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}")
#!/usr/bin/env bashset -euo pipefailFILE="invoice-1042.pdf"SHA256=$(shasum -a 256 "$FILE" | cut -d " " -f 1)SIZE=$(wc -c < "$FILE" | tr -d " ")# 1. Ask where to upload the fileANSWER=$(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 yetif [ "$(jq -r .status <<< "$SLOT")" = "upload" ]; thenHEADERS=()while IFS= read -r HEADER; doHEADERS+=(-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 filecurl -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": "<p>Thanks for your order. Your invoice is attached.</p>","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. On Linux without shasum, use sha256sum "$FILE" in its place. See 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, anddelivery_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.
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.dataconst { data, error } = await posthog.emails.send({to: email,templateKey: "password-reset",subject: "Reset your password",html: `<p>Reset your password <a href="${resetLink}">here</a>.</p>`,distinctId: userId,// The same key on every attempt, so a retried job never sends the email twiceidempotencyKey: `password-reset-${resetRequestId}`,// BullMQ retries the job, so the client doesn't retry on its ownmaxRetries: 0,})if (error) {throw RETRYABLE_CODES.has(error.code) ? error : new UnrecoverableError(`${error.code}: ${error.message}`)}return data.id},{ connection: { host: "localhost", port: 6379 } })
from celery import shared_taskfrom 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'<p>Reset your password <a href="{reset_link}">here</a>.</p>',distinct_id=user_id,# The same key on every attempt, so a retried task never sends the email twiceidempotency_key=f"password-reset-{reset_request_id}",# Celery retries the task, so the client doesn't retry on its ownmax_retries=0,)except EmailError as error:if error.code in RETRYABLE_CODES:# Waits 10, 20, 40, 80, then 160 secondsraise self.retry(exc=error, countdown=10 * 2**self.request.retries)# Any other code marks the task as failed, with no retryraisereturn result.id
class PasswordResetEmailJobinclude Sidekiq::Job# Five retries with Sidekiq's backoff finish within minutes, well inside the 7 dayssidekiq_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].freezesidekiq_retry_in do |_count, error|retryable = error.is_a?(PostHog::EmailError) && RETRYABLE_CODES.include?(error.code)retryable ? nil : :killenddef perform(user_id, email, reset_link, reset_request_id)$posthog.emails.send(to: email,template_key: 'password-reset',subject: 'Reset your password',html: %(<p>Reset your password <a href="#{reset_link}">here</a>.</p>),distinct_id: user_id,# The same key on every attempt, so a retried job never sends the email twiceidempotency_key: "password-reset-#{reset_request_id}",# Sidekiq retries the job, so the client doesn't retry on its ownmax_retries: 0)endend
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 argumentsRetry(EmailError),// Fail the job for goodPermanent(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<String, JobError> {let email = CodeEmail::new(&job.email, "password-reset", "Reset your password").html(format!(r#"<p>Reset your password <a href="{}">here</a>.</p>"#, 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)),}}
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' => "<p>Reset your password <a href=\"{$this->resetLink}\">here</a>.</p>",'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);
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 keyfunc (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: `<p>Reset your password <a href="` + args.ResetLink + `">here</a>.</p>`,DistinctID: args.UserID,// The same key on every attempt, so a retried job never sends the email twiceIdempotencyKey: "password-reset-" + args.ResetRequestID,// River retries the job, so the client doesn't retry on its ownMaxRetries: posthog.Ptr(0),})var emailErr *posthog.EmailErrorif errors.As(err, &emailErr) && !slices.Contains(retryableCodes, emailErr.Code) {// River doesn't run a cancelled job againreturn river.JobCancel(err)}return err}// Register the worker with river.AddWorker(workers, &PasswordResetWorker{PostHog: client}).
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<string> 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 = $"<p>Reset your password <a href=\"{resetLink}\">here</a>.</p>",DistinctId = userId,// The same key on every attempt, so a retried job never sends the email twiceIdempotencyKey = $"password-reset-{resetRequestId}",// Hangfire retries the job, so the client doesn't retry on its ownMaxRetries = 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<PasswordResetEmailJob>(job =>job.SendAsync(user.Id, user.Email, resetLink, resetRequestId));
defmodule MyApp.Workers.PasswordResetEmail douse 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.Workerdef 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} = argscase PostHog.Emails.send(to: email,template_key: "password-reset",subject: "Reset your password",html: ~s(<p>Reset your password <a href="#{reset_link}">here</a>.</p>),distinct_id: to_string(user_id),# The same key on every attempt, so a retried job never sends the email twiceidempotency_key: "password-reset-#{reset_request_id}",# Oban retries the job, so the SDK doesn't retry on its ownmax_retries: 0) do{:ok, _result} ->:ok{:error, %PostHog.Emails.Error{code: code} = error} when code in @retryable_codes ->{:error, error}{:error, error} ->{:cancel, error}endendend# 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 for your project.
For example, to see how many people finish a password reset after they get the email, build a funnel with these steps:
$workflows_email_delivered, filtered to$email_template_idequals your reset email's template ID. For an email your code writes, filter on$email_template_keyinstead.- 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.





