PostHog.Emails (posthog v2.22.2)

Copy Markdown View Source

Send transactional email, such as a password reset or a receipt, and read its status.

An email goes out in one of two forms:

  • A template made in PostHog, sent by its ID with :template_id and :template_data.
  • Content your code rendered, named by :template_key, with :subject and :html, :text or both. To send a React email, render it to HTML in your app, for example with @react-email/render, and pass the result as :html. The SDK adds no rendering.

Setup

  1. In PostHog, open the email template under Workflows, make it transactional, and copy its ID. :template_id is that UUID. The code form needs no template.

  2. Create a project secret API key (phs_...) with the "Send transactional email" preset (transactional_email:write) in your project settings. Add transactional_email:read too if you read email statuses with a key that can't send. Keys made with hog_flow:write still work. The project API key (phc_...) captures events but cannot send email.

  3. Set it as :secret_key in your PostHog config:

    config :posthog,
      api_host: "https://eu.i.posthog.com",
      api_key: "phc_...",
      secret_key: "phs_..."

Examples

Send a template made in PostHog:

{:ok, %PostHog.Emails.SendResult{id: message_id}} =
  PostHog.Emails.send(
    to: "user@example.com",
    template_id: "0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b",
    template_data: %{name: "Ada"},
    distinct_id: "user_123",
    idempotency_key: "welcome:user_123"
  )

Send content your code rendered:

PostHog.Emails.send(
  to: "user@example.com",
  template_key: "password-reset",
  subject: "Reset your password",
  html: rendered_html,
  distinct_id: "user_123",
  idempotency_key: "password-reset:#{reset.id}"
)

Copy finance and attach the receipt:

PostHog.Emails.send(
  to: "user@example.com",
  cc: "finance@example.com",
  template_key: "receipt",
  subject: "Your receipt",
  html: rendered_html,
  attachments: [
    %{filename: "receipt.pdf", content: File.read!(pdf_path), content_type: "application/pdf"}
  ],
  distinct_id: "user_123"
)

Read what happened to it:

{:ok, %PostHog.Emails.Status{status: status}} = PostHog.Emails.get(message_id)

Always pass :distinct_id. Without it, the email's events go to a person whose distinct ID is the email address, not to your user. The SDK never takes it from PostHog.set_context/2.

What a result means

{:ok, result} means PostHog queued the email. Delivery happens later: read it with get/2, or in the template's workflow in PostHog.

Where requests go

A client on PostHog Cloud sends to its region's app host, https://us.posthog.com or https://eu.posthog.com. For any other :api_host, such as a reverse proxy, set :app_host in the config, because email requests must not send the secret key to the proxy. Without it, a send returns the error missing_app_host.

:secret_key also turns on local feature flag evaluation, which fetches flag definitions from :api_host with that key. When :api_host is a proxy that must not see the key, set enable_local_evaluation: false as well.

Attachments

An email carries at most 10 files and 40 MB after Base64 encoding, about 29 MB of files. The SDK checks both before any request of a send with files, counting each file and body as Base64 and the subject as 75 bytes per 42 started, as PostHog does. Without :text, PostHog derives the text from :html and counts it too, so the SDK counts the HTML twice.

A send with files takes three steps:

  1. The SDK hashes each file with SHA-256 and asks PostHog which files it doesn't have yet.
  2. It uploads each of those straight to PostHog's file storage with a plain Req request, carrying only the headers PostHog gave. The upload doesn't go through :api_client_module, so no secret key or header of your client reaches the storage. A file PostHog already has, such as the same terms PDF sent to every customer, uploads nothing again.
  3. Once every upload succeeded, it sends the email, which names each file by its hash.

Uploads go only over https, so a file and its signed URL never travel unencrypted. When PostHog names a plain-HTTP upload URL, the SDK uploads nothing, sends nothing, and returns api_error on the attachment. An :app_host on plain HTTP, as in local development, allows plain-HTTP uploads too. An upload never follows a redirect, which would carry the file to another URL: the storage's redirect fails the upload with attachment_upload_failed.

Your app must be able to reach the storage host that PostHog's answer names directly: an upload doesn't go through a proxy, and it ignores your app's Req.default_options, which are meant for other requests. If an upload fails, the SDK sends nothing and returns attachment_upload_failed with what the storage answered. An upload gets the request timeout plus ten seconds per MB of the file. It retries network errors and storage answers of HTTP 429, 500, 502, 503 and 504, as a send retries, honouring Retry-After.

Timeouts, retries and idempotency

Each request times out after :email_request_timeout_ms (15 seconds by default). A send retries network errors, rate limits, an idempotency key still in flight and an unavailable service :email_request_max_retries times (2 by default), waiting about 1 and then 2 seconds, or the server's Retry-After when it is longer. A Retry-After over 30 seconds fails at once with :retry_after_ms set. A monthly quota and the day's upload quota are never retried. The upload steps of a send with files retry the same way.

Every attempt sends the same idempotency key, so a retry never sends twice. Without :idempotency_key, the SDK makes a UUID for the call. When a job runner such as Oban already retries the send, pass max_retries: 0 and an :idempotency_key that names the email, such as "welcome:user_123". A generated key doesn't survive a job retry.

Sends and status reads block the calling process until they finish. The SDK keeps no email queue.

Errors

Every failure returns {:error, %PostHog.Emails.Error{}}. Branch on :code. The ones a setup usually hits:

  • missing_secret_key: the config has no :secret_key.
  • missing_app_host: the :api_host is not PostHog Cloud. Set :app_host.
  • authentication_failed (401) or permission_denied (403): the key is wrong, or it lacks transactional_email:write.
  • not_found (404): the template ID is wrong, or transactional email is not enabled for the project.
  • client_disabled: the PostHog instance is not running or has no :api_key, so it sends nothing.
  • client_closed: the PostHog instance stopped during a call, so the call made no further request, and a send sent no email.

A send with files can also return:

  • too_many_attachments or message_too_large: over 10 files, or over 40 MB after Base64 encoding. The SDK checks both before any request, and PostHog checks them again.
  • attachment_upload_failed: an upload to PostHog's file storage failed, so no email was sent. The message has the storage's answer.
  • attachment_not_uploaded: PostHog has no uploaded file with a hash the send names.
  • upload_quota_exceeded (429): the project uploaded as many file bytes as it can today. Files PostHog already has don't count.
  • field_not_accepted: the project can't send files yet.

An option the SDK refuses returns an error with an invalid_* code, such as invalid_template_id, and the name :validation_error, before any request.

Testing

Requests to PostHog go through the configured :api_client_module, so a Mox mock of PostHog.API.Client sees them without network calls. Attachment uploads go to the storage host instead, so test a send with files against an answer that marks every file present.

Summary

Types

A file sent with the email. :content is the file's raw bytes, such as File.read!/1 returns. Don't pass content that is already Base64: the recipient would get the Base64 text.

Options for send/2. Pass :template_id or :template_key, never both.

What PostHog tracks for an email sent with :template_key. See :tracking in send_option/0.

Functions

Reads the status of an email that send/2 queued, for 30 days after the send.

Queues one email, from a template made in PostHog or from content your code rendered.

Types

attachment()

@type attachment() :: %{
  :filename => String.t(),
  :content => binary(),
  optional(:content_type) => String.t() | nil,
  optional(:content_id) => String.t() | nil
}

A file sent with the email. :content is the file's raw bytes, such as File.read!/1 returns. Don't pass content that is already Base64: the recipient would get the Base64 text.

send_option()

@type send_option() ::
  {:to, String.t()}
  | {:distinct_id, String.t() | nil}
  | {:idempotency_key, String.t() | nil}
  | {:max_retries, non_neg_integer() | nil}
  | {:template_id, String.t()}
  | {:template_data, map() | nil}
  | {:template_key, String.t()}
  | {:subject, String.t()}
  | {:html, String.t() | nil}
  | {:text, String.t() | nil}
  | {:from, String.t() | nil}
  | {:reply_to, String.t() | [String.t()] | nil}
  | {:cc, String.t() | [String.t()] | nil}
  | {:bcc, String.t() | [String.t()] | nil}
  | {:attachments, [attachment()] | nil}
  | {:sensitive, boolean() | nil}
  | {:tracking, tracking() | nil}
  | {:capture_engagement, boolean() | nil}

Options for send/2. Pass :template_id or :template_key, never both.

Every send takes:

  • :to - one recipient email address. Required.
  • :distinct_id - the recipient's distinct ID in your product. The email's events go to this person.
  • :idempotency_key - 1 to 255 visible ASCII characters. A send with a key PostHog already accepted queues nothing and returns the first send's result. Template sends and code sends share one set of keys: a key already used for another email returns idempotency_key_reused.
  • :max_retries - overrides the config's :email_request_max_retries for this send. 0 turns retries off.

A template made in PostHog takes:

  • :template_id - the UUID of a template made transactional in PostHog.
  • :template_data - a map of values for the template's {{ variables.* }} placeholders.

Content your code rendered takes:

  • :template_key - names the email, such as "password-reset", so its metrics, logs and status group under it in PostHog. Letters, digits, - and _, at most 400.
  • :subject - the subject line. Required.
  • :html and :text - the bodies. Give one or both. Without :text, PostHog derives it from :html.
  • :from - a verified sender, such as "Acme <security@example.com>". Without it, the project's default sender.
  • :reply_to - one address or a list of addresses.
  • :cc and :bcc - one address or a list of at most 10 bare addresses, such as "finance@example.com", that get a visible or a hidden copy.
  • :attachments - a list of files: at most 10 files and 40 MB per email after Base64 encoding, about 29 MB of files. Each is a map with :filename, :content (the file's bytes, such as File.read!/1 returns), and optionally :content_type, such as "application/pdf", and :content_id, which shows the file inline: reference it in :html as <img src="cid:logo"> with content_id: "logo". Pass raw bytes, not Base64. PostHog can't fetch a file from a path or URL. A file the SDK can't send returns the error code invalid_attachment. See "Attachments" in PostHog.Emails for how files travel.
  • :sensitive - true when the email carries login links, reset tokens or codes. A sensitive email keeps its links unchanged unless :tracking turns clicks on, leaves its subject off engagement events, and keeps its content out of logs. Left out, the email takes the setting of the template made in PostHog whose key matches :template_key, and is sensitive when no template matches. Sent only when you set it, and needs a PostHog version that takes it.
  • :tracking - what PostHog tracks for the email. Left out, PostHog counts opens and captures engagement events, and tracks clicks only when the email isn't sensitive. true turns on opens, clicks and engagement events, even for a sensitive email. false turns them all off: the email has no open pixel and no rewritten links, and PostHog captures no engagement events for it. A map such as %{clicks: true} sets :opens (default true), :clicks (default: on unless the email is sensitive) and :engagement (default true) one by one. Turn clicks on for a sensitive email only when its links are safe to rewrite. Click tracking needs open tracking. A project whose admin turned engagement capture off captures nothing, whatever the send says. Sent only when you set it, and needs a PostHog version that takes it.
  • :capture_engagement - deprecated: use tracking: %{engagement: false} instead. Whether PostHog captures the email's engagement events. It still works, but a send can't set both. Sent only when you set it.

An option set to nil counts as left out, and so does an empty :reply_to, :cc, :bcc or :attachments list. A PostHog version that doesn't take a field yet, such as :attachments, refuses the send with an error whose :field names it, and never drops the field to send the rest.

tracking()

@type tracking() ::
  boolean()
  | %{
      optional(:opens) => boolean() | nil,
      optional(:clicks) => boolean() | nil,
      optional(:engagement) => boolean() | nil
    }

What PostHog tracks for an email sent with :template_key. See :tracking in send_option/0.

Functions

get(name \\ PostHog, message_id)

Reads the status of an email that send/2 queued, for 30 days after the send.

Returns {:ok, %PostHog.Emails.Status{}} or {:error, %PostHog.Emails.Error{}}. The error code is not_found when no email of this project has the ID, when the email is older than 30 days, or for a few seconds after the send. A key with only transactional_email:read can read statuses but not send. Network errors, rate limits and an unavailable service are retried.

Examples

{:ok, %PostHog.Emails.Status{status: "bounced", reason: reason}} =
  PostHog.Emails.get(message_id)

send(name \\ PostHog, options)

Queues one email, from a template made in PostHog or from content your code rendered.

Returns {:ok, %PostHog.Emails.SendResult{}} once PostHog queued the email, or {:error, %PostHog.Emails.Error{}}. See send_option/0 for the options. name is the PostHog instance to send through, PostHog by default.

Examples

PostHog.Emails.send(
  to: "user@example.com",
  template_id: "0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b",
  distinct_id: "user_123"
)

PostHog.Emails.send(MyPostHog,
  to: "user@example.com",
  template_key: "receipt",
  subject: "Your receipt",
  html: html,
  distinct_id: "user_123"
)