Send transactional emails with Elixir

The Elixir SDK sends transactional emails from version 2.20.0. 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 Elixir app with the posthog Hex package.
Read https://posthog.com/docs/workflows/installation/elixir.md first. Follow it over anything you remember about PostHog.
- Reuse the app's :posthog config. Add secret_key from the POSTHOG_PROJECT_SECRET_API_KEY environment variable in config/runtime.exs. Set enable_local_evaluation: false unless the app evaluates feature flags locally.
- Send only from server code. Never put the secret key in source code or in anything sent to 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.
- PostHog.Emails.send/2 returns {:ok, %PostHog.Emails.SendResult{id: id}} or {:error, %PostHog.Emails.Error{}} and doesn't raise. 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(), as a string. 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 an ExUnit test that starts a PostHog instance with an api_client_module that adds a Req.Test plug, and checks the request.
Send each email's subject and HTML from code, with a template_key that names it, such as password-reset. Only send a template_id if I tell you the email is a template in PostHog. Don't create the API key. I create it.

Install

Add posthog to your dependencies in mix.exs:

Elixir
def deps do
[
{:posthog, "~> 2.20"}
]
end

Set up the client

Add your project secret API key to the PostHog config that your app already has. The project token keeps capturing events. The secret key sends email, so read it from the environment and keep it on your server.

config/runtime.exs
config :posthog,
api_host: "https://us.i.posthog.com",
api_key: "<ph_project_token>",
secret_key: System.fetch_env!("POSTHOG_PROJECT_SECRET_API_KEY"),
# The SDK doesn't load flag definitions with the secret key
enable_local_evaluation: false

Keep enable_local_evaluation: false unless your app evaluates feature flags locally. With local evaluation on, the SDK polls flag definitions with the secret key, and a key with only the Transactional email scope can't read them. If you do evaluate flags locally, give the key the Feature flag read scope too.

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

Elixir
def send_password_reset(user, reset_link, reset_request_id) do
case PostHog.Emails.send(
to: user.email,
# Names the email, so PostHog groups its sends and metrics
template_key: "password-reset",
subject: "Reset your password",
html: ~s(<p>Reset your password <a href="#{reset_link}">here</a>. The link works for 1 hour.</p>),
distinct_id: to_string(user.id),
# Identifies this one email, so a retry never sends it twice
idempotency_key: "password-reset-#{reset_request_id}"
) do
{:ok, result} ->
{:ok, result.id}
# A %PostHog.Emails.Error{}. Branch on error.code
{:error, error} ->
{:error, error}
end
end

For a longer email, render the HTML first with EEx, Phoenix templates, or another template engine, and pass the result as html.

send/2 doesn't raise. It returns {:ok, %PostHog.Emails.SendResult{}} or {:error, %PostHog.Emails.Error{}}. result.id is the message ID. The error's code is one of the codes in the errors table. An option that the SDK refuses returns an invalid_* code before any request.

To send through a named PostHog instance instead of the default one, pass its name first: PostHog.Emails.send(MyPostHog, options).

Fields use snake case, such as template_key and distinct_id. See send emails from code for every field, and the quick start for the version each one needs.

Write automated tests

Every request goes through the config's api_client_module. Wrap the default client with a Req.Test plug to see exactly what your code sends, with no network call. Req.Test needs the plug package, which a Phoenix app already has. This tests your integration, not delivery. To test delivery, send a real email to your own address and open the send in the Log tab.

test_mode: true keeps captured events in memory, but it doesn't stop email requests. Use the plug for those.

Elixir
defmodule MyApp.PostHogTestClient do
# The default client, with Req.Test in place of the network
@behaviour PostHog.API.Client
@impl true
def client(api_key, api_host) do
default = PostHog.API.Client.client(api_key, api_host)
%{default | client: Req.merge(default.client, plug: {Req.Test, __MODULE__})}
end
@impl true
defdelegate request(client, method, url, opts), to: PostHog.API.Client
end
defmodule MyApp.PasswordResetEmailTest do
use ExUnit.Case, async: true
setup do
config =
PostHog.Config.validate!(
supervisor_name: MyApp.TestPostHog,
api_key: "phc_test",
secret_key: "phs_test",
enable_local_evaluation: false,
api_client_module: MyApp.PostHogTestClient
)
start_supervised!({PostHog.Supervisor, config})
:ok
end
test "sends the email with its idempotency key" do
test_pid = self()
Req.Test.expect(MyApp.PostHogTestClient, fn conn ->
{:ok, body, conn} = Plug.Conn.read_body(conn)
send(test_pid, {:email_request, Plug.Conn.get_req_header(conn, "idempotency-key"), body})
Req.Test.json(conn, %{message_id: "msg_1", replayed: false})
end)
assert {:ok, %PostHog.Emails.SendResult{id: "msg_1"}} =
PostHog.Emails.send(MyApp.TestPostHog,
to: "jane@example.com",
template_key: "password-reset",
subject: "Reset your password",
text: "Reset it here.",
idempotency_key: "password-reset-1"
)
assert_received {:email_request, ["password-reset-1"], body}
assert %{"to" => "jane@example.com"} = Jason.decode!(body)
end
end

Next

Still have questions?

Was this page useful?