Send transactional emails with Ruby

The Ruby SDK sends transactional emails from version 3.30.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 Ruby app with the posthog-ruby gem.
Read https://posthog.com/docs/workflows/installation/ruby.md first. Follow it over anything you remember about PostHog.
- Reuse the app's PostHog::Client. Add secret_key from the POSTHOG_PROJECT_SECRET_API_KEY environment variable. The client also loads feature flag definitions with this key, so tell me to give the key the Feature flag read scope too.
- Send only from server code. Never put the secret key in code or config that reaches 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.
- emails.send returns a SendResult and raises PostHog::EmailError when PostHog doesn't queue the email. Branch on error.code, never on the 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(). 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 a test that stubs the send request with WebMock 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 this to your Gemfile, then run bundle install:

Ruby
gem "posthog-ruby", "~> 3.35"

Set up the client

Add your project secret API key to the PostHog client that your app already has. The project token keeps capturing events. The secret key sends email, so keep it on your server and never ship it to the browser.

Ruby
require 'posthog'
$posthog = PostHog::Client.new({
api_key: '<ph_project_token>',
host: 'https://us.i.posthog.com',
secret_key: ENV.fetch('POSTHOG_PROJECT_SECRET_API_KEY')
})

When secret_key is set, the client also loads flag definitions with it for local evaluation when it starts, and polls them after that. Give the key the Feature flag read scope too, or each of those loads fails.

Shut the client down when your app exits, not after each send. 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.

Use in Rails

With posthog-rails, reuse the client initialized by PostHog.init. Add the secret key to your existing initializer:

config/initializers/posthog.rb
PostHog.init do |config|
config.api_key = "<ph_project_token>"
config.host = "https://us.i.posthog.com"
config.secret_key = ENV.fetch("POSTHOG_PROJECT_SECRET_API_KEY")
end

Use PostHog.emails wherever the examples below use $posthog.emails. Rails handles client shutdown.

Pass email options such as app_host and email_request_max_retries as a hash to PostHog.init(...), not in its configuration block.

Send an email

Ruby
def send_password_reset(user, reset_link, reset_request_id)
# Raises PostHog::EmailError when PostHog doesn't queue the email. Branch on error.code.
result = $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: %(<p>Reset your password <a href="#{reset_link}">here</a>. The link works for 1 hour.</p>),
distinct_id: user.id.to_s,
# Identifies this one email, so a retry never sends it twice
idempotency_key: "password-reset-#{reset_request_id}"
)
result.id
end

send returns a SendResult, and result.id is the message ID. A result means PostHog queued the email, not that it delivered it. When PostHog doesn't queue the email, send raises PostHog::EmailError, and its code is one of the codes in the errors table. A wrong argument raises ArgumentError before any request.

For a longer email, render the HTML first with your template engine, such as ERB or Action Mailer views, and pass the result as html.

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

The client sends email with Ruby's Net::HTTP, so WebMock can stub the request and show exactly what your code sends, with no network call. This tests your integration, not delivery. To test delivery, send a real email to your own address and check the Log on the Transactional tab.

test_mode: true doesn't stop email requests or flag definition loads, so stub both.

Ruby
require 'posthog'
require 'webmock/rspec'
RSpec.describe 'password reset email' do
let(:send_url) { %r{/messaging/send/email/\z} }
let(:posthog) { PostHog::Client.new(api_key: 'phc_test', secret_key: 'phs_test', test_mode: true) }
before do
stub_request(:get, %r{/flags/definitions}).to_return(status: 200, body: '{"flags":[]}')
stub_request(:post, send_url).to_return(status: 202, body: '{"message_id":"msg_1","replayed":false}')
end
after { posthog.shutdown }
it 'sends the email once, with its idempotency key' do
result = posthog.emails.send(
to: 'jane@example.com',
template_key: 'password-reset',
subject: 'Reset your password',
html: '<p>Reset your password.</p>',
idempotency_key: 'password-reset-1'
)
expect(result.id).to eq('msg_1')
expect(a_request(:post, send_url).with(headers: { 'Idempotency-Key' => 'password-reset-1' }))
.to have_been_made.once
end
end

Next

Still have questions?

Was this page useful?