# Send Email with Ruby on Rails Using an API

> Send email with Ruby on Rails through an email API: a custom ActionMailer delivery method, so mailers and deliver_later use Cresca, with idempotent retries.

Canonical: https://www.cresca.xyz/blog/send-email-rails
Author: Lalit Kumar Jangid
Published: 2026-10-27
Last updated: 2026-10-30

In Rails, ActionMailer builds the email and a delivery method decides how it leaves the app. That split is what makes it easy to **send email with Ruby on Rails** through an email API instead of SMTP: swap the delivery method and leave everything else alone. Mailers, views, layouts, previews and `deliver_later` calls keep working, and each message goes out through Cresca from your own verified domain. Below you add a `:cresca` delivery method, make mailer sends idempotent so job retries are safe, and handle templates, attachments and batches the Rails way.

**What changes in your app**

- Two files in `lib/` and one initializer that calls `ActionMailer::Base.add_delivery_method`.
- `config.action_mailer.delivery_method = :cresca` in `config/environments/production.rb`.
- Mailers stay as they are, attachments included.
- An optional header in each mailer action that makes a retried delivery job harmless.

## Before you start

- **Rails 7 or later.** No gem to add; the client is standard-library Ruby.
- **A verified domain and sender.** In [Sending Domains](https://app.cresca.xyz/sending-domains), add your domain and publish the DKIM, MAIL FROM and ownership records shown (Cresca can do it for you on Cloudflare DNS). Add a sender such as `hello@acme.com`; your mailers' `from` must be an active sender on that domain.
- **A *Sending access* key** from [API keys](https://app.cresca.xyz/api-keys). It can send but not read logs or edit templates, starts with `cr_live_` and is shown once.

Follow the [email API quickstart](https://www.cresca.xyz/docs/quickstart) for the account steps.

## Step 1: add the API client to lib/

This is the same client as in the [plain Ruby tutorial](https://www.cresca.xyz/blog/send-email-ruby), saved as `lib/cresca.rb`. It rescues timeouts and connection errors, retries `429` and `5xx` with backoff, and raises `Cresca::Error` carrying the API's error name in `code`:

```ruby
# lib/cresca.rb: a small client for the Cresca email API.
require "net/http"
require "json"

module Cresca
  API_URL = "https://api.cresca.xyz/api/v1"
  ATTEMPTS = 4
  NETWORK_ERRORS = [Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError, IOError].freeze

  class Error < StandardError
    attr_reader :status, :code

    def initialize(status, code, message)
      super("#{status} #{code}: #{message}")
      @status = status
      @code = code
    end
  end

  def self.post(path, payload, idempotency_key: nil)
    (1..ATTEMPTS).each do |attempt|
      begin
        res = request(path, payload, idempotency_key)
      rescue *NETWORK_ERRORS
        # Network error or timeout: the idempotency key makes a retry safe.
        raise if attempt == ATTEMPTS
        sleep backoff(attempt)
        next
      end

      body = (JSON.parse(res.body) rescue {})
      return body if res.is_a?(Net::HTTPSuccess)

      status = res.code.to_i
      name = body["name"] || "unknown_error"
      retryable = status >= 500 ||
                  (status == 429 && name != "monthly_quota_exceeded") ||
                  name == "concurrent_idempotent_requests"
      raise Error.new(status, name, body["message"]) if !retryable || attempt == ATTEMPTS

      sleep(res["retry-after"] ? res["retry-after"].to_f : backoff(attempt))
    end
  end

  def self.request(path, payload, idempotency_key)
    uri = URI("#{API_URL}#{path}")
    headers = {
      "Authorization" => "Bearer #{ENV.fetch('CRESCA_API_KEY')}",
      "Content-Type" => "application/json"
    }
    headers["Idempotency-Key"] = idempotency_key if idempotency_key
    Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
      http.post(uri.path, payload.to_json, headers)
    end
  end

  # 1s, 2s, 4s... plus up to 250 ms of jitter.
  def self.backoff(attempt)
    2**(attempt - 1) + rand / 4
  end
end
```

It reads the key from `ENV`. If your team keeps secrets in Rails credentials instead, run `bin/rails credentials:edit`, add the key under `cresca: api_key:`, and change the `ENV.fetch` line to `Rails.application.credentials.dig(:cresca, :api_key)`. Either way the key stays out of the repository in plain text.

## Step 2: send email with Ruby on Rails through a delivery method

ActionMailer accepts any class that responds to `new(settings)` and `deliver!(mail)`. The `mail` it receives is the finished `Mail::Message`, after your views and layouts have rendered. This class reads the addresses, subject, HTML and text parts and attachments off it and posts them to Cresca:

```ruby
# lib/cresca_delivery.rb: an ActionMailer delivery method for the Cresca API.
require_relative "cresca"

class CrescaDelivery
  attr_reader :settings

  def initialize(settings)
    @settings = settings
  end

  def deliver!(mail)
    payload = {
      from: mail[:from].to_s,
      to: mail.to,
      cc: mail.cc,
      bcc: mail.bcc,
      reply_to: mail.reply_to,
      subject: mail.subject,
      html: body_for(mail, "text/html"),
      text: body_for(mail, "text/plain")
    }.compact

    attachments = mail.attachments.map do |attachment|
      {
        filename: attachment.filename,
        content: [attachment.decoded].pack("m0"),
        content_type: attachment.mime_type
      }
    end
    payload[:attachments] = attachments if attachments.any?

    Cresca.post("/emails", payload, idempotency_key: mail.header["X-Idempotency-Key"]&.value)
  end

  private

  def body_for(mail, mime_type)
    if mail.multipart?
      part = mime_type == "text/html" ? mail.html_part : mail.text_part
      part&.decoded
    elsif (mail.mime_type || "text/plain") == mime_type
      mail.body.decoded
    end
  end
end
```

Register it in an initializer and point production at it:

```ruby
# config/initializers/cresca.rb
require Rails.root.join("lib/cresca_delivery").to_s

ActionMailer::Base.add_delivery_method :cresca, CrescaDelivery
```

```ruby
# config/environments/production.rb
config.action_mailer.delivery_method = :cresca
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { host: "acme.com", protocol: "https" }
```

Leave `:letter_opener` or `:test` in development and test so local runs never send real mail. If `config/application.rb` calls `config.autoload_lib` (apps generated with Rails 7.1 or later do), add both files to its ignore list, for example `config.autoload_lib(ignore: %w[assets tasks cresca.rb cresca_delivery.rb])`, because the initializer already requires them and they should not be autoloaded as well.

## Step 3: keep writing mailers as usual

Nothing about your mailers changes, apart from an optional header. The `default from:` has to be an active sender on your verified domain:

```ruby
class UserMailer < ApplicationMailer
  default from: "Acme <hello@acme.com>"

  def welcome
    @user = params[:user]
    headers["X-Idempotency-Key"] = "welcome/#{@user.id}"
    mail(to: @user.email, subject: "Welcome to Acme")
  end
end

UserMailer.with(user: user).welcome.deliver_later
```

The `X-Idempotency-Key` header is a hand-off between the mailer and the delivery method. `deliver!` reads it and sends it to Cresca as the `Idempotency-Key` request header; it is not copied into the email. `deliver_later` enqueues a delivery job, and if that job runs again after a timeout, Cresca sees the same key and returns the first result instead of sending a duplicate. Keys last 24 hours and should come from the record, as in `welcome/#{@user.id}`. ERB's `<%= %>` escapes output in mailer views, so user data is safe there. The `default_url_options` host in production.rb is what `_url` helpers in mailer views use for absolute links.

## Attachments from your mailers

Keep using `attachments["invoice.pdf"] = pdf_bytes` in mailer actions. The delivery method base64-encodes each one and sends `filename`, `content` and `content_type` from the attachment's MIME type. Cresca accepts up to 20 files and 7 MB in total per email, refuses executable types such as .exe and .js, and does not yet support attaching by URL. One gap in this short version: `attachments.inline` files go out as regular attachments. Cresca shows an image inline when the attachment has a `content_id` referenced as `<img src="cid:logo">`, so add `content_id` from `attachment.content_id` in `deliver!` if you need that.

## Send a Cresca template from Rails

Mailer views suit emails that developers own. When a designer or marketer needs to edit an email without a deploy, build it in Cresca's template editor instead, with triple-brace placeholders such as `{{{RESET_LINK}}}`, and publish. Rails then calls the client directly with the alias and the values. Only the *published* version is sent, so drafts are safe to work on. Cresca HTML-escapes values the way ERB does, and a variable missing with no fallback raises `Cresca::Error` with `validation_error` (422) and the variable's name. Details in [templates and variables](https://www.cresca.xyz/docs/templates).

```ruby
Cresca.post("/emails", {
  to: user.email,
  template: {
    id: "password-reset", # the template's alias or id
    variables: { NAME: user.first_name, RESET_LINK: edit_password_url(token: token) }
  }
}, idempotency_key: "password-reset/#{reset_request.id}")
```

## Send a batch of up to 100 emails

For a digest to many users, skip ActionMailer and call `POST /emails/batch`. It takes up to 100 emails per request, matching `find_in_batches(batch_size: 100)`. Each item has the same fields as a single send except `attachments` and `scheduled_at`. One invalid item rejects the whole batch, and the error message gives its zero-based index. On success you get `{"data": [{"id": "..."}, ...]}` in the same order. A batch counts as a single request against your rate limit, which is how you get to thousands of emails a minute.

```ruby
User.where(wants_summary: true).find_in_batches(batch_size: 100).with_index do |users, index|
  emails = users.map do |user|
    {
      from: "Acme <hello@acme.com>",
      to: user.email,
      subject: "Your weekly summary",
      html: ApplicationController.render(template: "summaries/weekly", layout: false, assigns: { user: user })
    }
  end
  Cresca.post("/emails/batch", emails, idempotency_key: "weekly-summary/#{Date.current}/#{index}")
end
```

`ApplicationController.render` renders a regular view outside a request, so the summary HTML still lives in `app/views`. Run this from a scheduled job, not a controller. The key combines `Date.current` with the batch index, so a same-day rerun over the same users gets the earlier results back instead of sending again.

## Why not Rails' SMTP settings?

The built-in `:smtp` delivery method works with any SMTP server, but failures come back as `Net::SMTP` exceptions with little detail, and SMTP has no way to make a retried delivery idempotent. The delivery method above gives you JSON errors with a stable `name` and safe retries. Cresca has no SMTP relay yet, so `smtp_settings` can't point at it anyway.

## Errors to handle when you send email with Rails

Here is what happens to a `deliver_later` job for each common error. All error names are on the [errors page](https://www.cresca.xyz/docs/errors).

| Error name | Status | Inside the delivery job | What to change |
| --- | --- | --- | --- |
| `invalid_from_address` | 403 | `Cresca::Error` raised, no client retry | The mailer's `from`: use an active sender on a verified domain |
| `validation_error` | 422 | `Cresca::Error` raised, no client retry | The invalid field, or the missing template variable |
| `missing_required_field` | 422 | `Cresca::Error` raised, no client retry | Set `to`, `from` and `subject` (or use a template that does) |
| `rate_limit_exceeded` | 429 | Client waits for `retry-after` | Nothing; batch bulk sends if it is frequent |
| `monthly_quota_exceeded` | 429 | `Cresca::Error` raised, no client retry | The plan's email allowance for the month is used |
| `concurrent_idempotent_requests` | 409 | Client retries shortly | Nothing; that key is still in flight |
| `application_error` | 5xx | Client backs off and retries | Nothing; Cresca's side |

Because `raise_delivery_errors` is true, a `Cresca::Error` fails the job. Your error tracker sees it, and your queue backend or a `retry_on` rule can run it again. The 4xx rows will fail on every retry until you fix the cause. Addresses on your suppression list (old hard bounces, complaints and unsubscribes) are skipped without an error. See [suppression](https://www.cresca.xyz/docs/suppression).

## Check that the email was delivered

A `200` from Cresca means accepted, not delivered. This short delivery method throws away the returned id, so if you want to trace emails from your logs, have `deliver!` write the id with `Rails.logger`. [Transactional](https://app.cresca.xyz/transactional) in the Cresca app shows each email's timeline, and with a full-access key you can fetch one from a terminal:

```bash
curl https://api.cresca.xyz/api/v1/emails/4ef9a417-02e9-4d39-ad75-9611e0fcc33c \
  -H "Authorization: Bearer $CRESCA_API_KEY"
```

The `last_event` field begins at `queued`, moves to `sent`, and ends at `delivered` or `bounced`. See [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle) for the full list.

## Frequently asked questions

### Do deliver\_later and Active Job retries still work?

Yes. deliver\_later enqueues the delivery job as before, and the job calls CrescaDelivery#deliver!. Set X-Idempotency-Key in the mailer so a job that runs twice within 24 hours still sends one email.

### Do mailer previews change?

No. Previews in test/mailers/previews render the message without delivering it, so they don't touch the delivery method. To send a real test, run a mailer from bin/rails console in an environment set to :cresca.

### Should the key live in credentials or an environment variable?

Either works. ENV suits platforms that inject secrets at deploy time. Credentials suit teams already using config/credentials; read it with Rails.application.credentials.dig(:cresca, :api\_key) in lib/cresca.rb.

## The same tutorial in other languages

[Node.js](https://www.cresca.xyz/blog/send-email-nodejs) · [Python](https://www.cresca.xyz/blog/send-email-python) · [PHP](https://www.cresca.xyz/blog/send-email-php) · [Go](https://www.cresca.xyz/blog/send-email-golang) · [Ruby](https://www.cresca.xyz/blog/send-email-ruby) · [Java](https://www.cresca.xyz/blog/send-email-java) · [C# and .NET](https://www.cresca.xyz/blog/send-email-csharp) · [Next.js](https://www.cresca.xyz/blog/send-email-nextjs) · [Laravel](https://www.cresca.xyz/blog/send-email-laravel) · [Django](https://www.cresca.xyz/blog/send-email-django)

The [send email API guide](https://www.cresca.xyz/blog/send-email-api) covers every field with cURL. The [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) explains the bigger picture, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) goes deeper into the trade-off with `:smtp`.

## Start sending

Add the two lib files and the initializer, flip production to `:cresca`, and deploy. **[Create your Cresca account](https://app.cresca.xyz/signup)**; it's free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. Then see the [quickstart](https://www.cresca.xyz/docs/quickstart) or the [API docs](https://www.cresca.xyz/docs).
