Send transactional emails with Rails
Contents
The posthog-rails gem adds a :posthog delivery method to Action Mailer. Your mailers, views, previews, and deliver_later stay as they are, and each mail goes out as one PostHog transactional email. Before you start, create a project secret API key, and verify the domain of the From address your mailers use. PostHog refuses a send from any other domain with sender_not_verified.
Install
Add both gems to your Gemfile:
Set up the client
The delivery method sends through the client that PostHog.init creates. Set secret_key on it to your project secret API key, as use in Rails shows. To send an email from your code without a mailer, call PostHog.emails.send as the Ruby page describes.
Turn on the delivery method
Your mailers don't change:
UserMailer.welcome(user).deliver_now sends the email. After the send, the mail's message_id is PostHog's message ID.
Name your emails
PostHog groups the metrics, logs, and status of each email by its template key. The delivery method uses the first key that it finds:
The
X-PostHog-Template-Keyheader of the mail, such aspassword-reset. It can only have letters, digits, hyphens, and underscores, at most 256.The mailer and the action, such as
user_mailer-welcomeforUserMailer#welcome, cut to 256 characters.The
default_template_keysetting, for mail that doesn't come from a mailer:config/environments/production.rbaction-mailer.
Set send options with headers
Headers are the one place a mailer can set options for one email. The delivery method reads these headers and doesn't send them:
| Header | Sets |
|---|---|
X-PostHog-Distinct-Id | The recipient's distinct ID, so the email's engagement events go to that person. Without it, they go to a person whose distinct ID is the email address. |
X-PostHog-Template-Key | The template key. |
X-PostHog-Idempotency-Key | The idempotency key. For 24 hours after PostHog queues an email, a send of the same email with the same key sends nothing, and a send of a different email with it gets idempotency_key_reused. See retry safely. |
X-PostHog-Sensitive | true or false: whether the email carries login links, reset tokens, or codes. See sensitive emails. |
X-PostHog-Track-Opens | true or false: whether PostHog adds its open pixel to count opens. |
X-PostHog-Track-Clicks | true or false: whether PostHog rewrites the links to count clicks. Without it, PostHog tracks clicks only when the email isn't sensitive. |
X-PostHog-Capture-Engagement | true or false: whether PostHog captures the email's engagement events. |
The last four set sensitive and tracking as on the Ruby page. Leave a header out and PostHog decides. Without X-PostHog-Sensitive, an email takes the Protect sensitive data setting of the template in your project that has its template key, and is sensitive when no template has that key. So PostHog doesn't track clicks on mail named after its mailer, such as user_mailer-welcome. Set it to false for mail that carries no secrets. The delivery method refuses X-PostHog-Track-Opens: false with X-PostHog-Track-Clicks: true as unsupported_header, because click tracking needs open tracking.
Send with deliver_later
A job runner retries a failed deliver_later job, and each retry is a new send. Set X-PostHog-Idempotency-Key from a stable ID, such as the record ID and the mailer name, so a retry within 24 hours never sends the email twice:
Without the header, the client makes a key that covers only its own retries within one send. A retry has to render the same mail: when the view renders a timestamp or a fresh token, the retry gets idempotency_key_reused, which means the first attempt was probably sent, so don't send it again by hand.
What PostHog can't send
PostHog sends one email to one recipient, with an HTML body, a text body, or both, and copies to up to 10 Cc and 10 Bcc addresses. The delivery method refuses a mail that PostHog can't send as written, before any request. Apart from the display names of recipients and the headers that Mail writes, such as Message-ID and Date, it never drops part of a mail. It raises PostHog::Rails::UnsupportedMailError, and error.refusal tells you why:
refusal | When |
|---|---|
multiple_to | The mail has no To address, or more than one. Send one mail to each recipient. |
unsupported_header | The mail has a header that PostHog can't send, such as X-Campaign or Content-Language. The headers that Mail writes itself, such as Message-ID, Date, and Content-Type, are ignored. |
inline_without_cid | An inline attachment has no content ID. |
envelope_mismatch | smtp_envelope_from, Sender, or Return-Path differs from From, or smtp_envelope_to differs from the To, Cc, and Bcc addresses. |
unsupported_priority | The mail sets a priority other than normal. |
unsupported_part | The mail has a part other than one HTML body, one text body, and attachments, such as a calendar invite, a signed message, an attachment without a filename, or a text and an HTML body that aren't alternatives of each other. |
template_unsupported | The mail sets X-PostHog-Template-Id. To send a template made in PostHog, call PostHog.emails.send with template_id. |
invalid_template_key | X-PostHog-Template-Key has characters that a template key can't have, or more than 256. |
invalid_mail | A field breaks a rule of the send, such as a mail without a subject or an X-PostHog-Idempotency-Key with a space. error.message names the field. |
The display names of recipients, such as Ana <ana@example.com>, are dropped. The display name of From is kept.
PostHog refuses a send with attachments, so a mail with an attachment raises a DeliveryError, and PostHog sends nothing. See copies and attachments.
Errors
When PostHog doesn't queue the email, the delivery method raises PostHog::Rails::DeliveryError. It has the status, code, detail, and attr of the errors table, retry_after when PostHog asked the client to wait, and retryable?. The client already retries network errors, rate limits, and a 503 two times before it raises.
When retryable? is true, PostHog might have queued the email, so retry the job, after retry_after when it is set. A mail with a stable X-PostHog-Idempotency-Key is then sent at most once while PostHog remembers the key. A permanent error fails again on each attempt, so log and report it and end the job, as the handler also does after the fifth attempt. PostHog.capture_exception sends it to Error Tracking, on every Rails version that posthog-rails supports. If the job raises the error again, your queue backend, such as Sidekiq, retries it with its own policy. A refused mail fails the same way on every attempt too, so the handler reports UnsupportedMailError and ends the job. The delivery method defines its errors when Action Mailer loads, so add the handler in an on_load block. It handles ActionMailer::MailDeliveryJob, the job deliver_later uses since config.load_defaults 6.0:
When raise_delivery_errors is false, Action Mailer doesn't raise either error. The delivery method logs it to PostHog::Logging.logger instead, and the mail is not sent.





