# Send Email with Ruby: A Complete API Tutorial

> Send email with Ruby using Net::HTTP and an email API: HTML, templates, attachments, batches and safe retries with no gems, plus a Sidekiq job example.

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

This guide is for plain Ruby: a script, a Rake task, a Sinatra or Hanami app, a worker process. To **send email with Ruby** there you don't need `Net::SMTP`, a mail server or a gem. `Net::HTTP` from the standard library can call an email API directly. Cresca takes the JSON, returns an id and delivers the message from your verified domain within seconds. Below: a small client module, then HTML, templates, attachments, batches and a Sidekiq job.

**The short version**

- POST JSON to `https://api.cresca.xyz/api/v1/emails` with `Net::HTTP` and a bearer token.
- Only `net/http` and `json` are required, both part of Ruby.
- Rescue timeouts, retry 429 and 5xx, and send an `Idempotency-Key` so retries are safe.

## Before you start

- **Ruby.** Any supported version; nothing here needs a Gemfile.
- **Your domain and a sender.** In Cresca's [Sending Domains](https://app.cresca.xyz/sending-domains), add the domain and publish the DKIM, MAIL FROM and ownership records it shows. On Cloudflare DNS, Cresca can publish them for you. Then add a sender such as `hello@acme.com`; every `from` has to be an active sender on a verified domain.
- **A *Sending access* key** from [API keys](https://app.cresca.xyz/api-keys). It can send but not read logs or change templates. It starts with `cr_live_` and is shown only once.

Export the key as `CRESCA_API_KEY`. The code reads it with `ENV.fetch`, which raises `KeyError` if it is missing, so a misconfigured server fails loudly on the first send instead of posting an empty bearer token. The [email API quickstart](https://www.cresca.xyz/docs/quickstart) has the account steps in detail.

## Send email with Ruby: the basic request

```ruby
require "net/http"
require "json"

res = Net::HTTP.post(
  URI("https://api.cresca.xyz/api/v1/emails"),
  {
    from: "Acme <hello@acme.com>",
    to: "ana@example.com",
    subject: "Welcome to Acme",
    html: "<p>Hi Ana, your account is ready.</p>"
  }.to_json,
  "Authorization" => "Bearer #{ENV.fetch('CRESCA_API_KEY')}",
  "Content-Type" => "application/json"
)

body = JSON.parse(res.body)
raise "#{body['name']}: #{body['message']}" unless res.is_a?(Net::HTTPSuccess)
puts body["id"]
```

`Net::HTTP.post` is the one-call form of the library. It returns a response rather than raising on HTTP errors, hence the `Net::HTTPSuccess` check. It also uses the library's default timeouts of 60 seconds, too long for anything a user waits on, so the client below sets its own. A successful call returns `200 OK` and a body like `{"id": "4ef9a417-..."}`. If you only pass `html`, Cresca writes the plain-text part; pass `text` to write it yourself.

## A Ruby client with timeouts and retries

For anything beyond a test script, wrap the call in a module. This one does three jobs:

- **Sends an `Idempotency-Key`.** When the response is lost after Cresca has accepted the email, a retry with the same key returns the original result and the email is not sent again. Keys live for 24 hours. Base them on the event (`welcome/user-123`, `invoice/inv-2026-0042`), never on `Time.now` or `SecureRandom`. See [idempotency](https://www.cresca.xyz/docs/idempotency).
- **Retries the right failures.** Network trouble arrives in Ruby as exceptions, so `NETWORK_ERRORS` lists the ones to rescue: `Net::OpenTimeout`, `Net::ReadTimeout`, `SocketError`, plus `SystemCallError` for things like `ECONNRESET`. HTTP failures arrive as a response, and the module retries `5xx`, `429 rate_limit_exceeded` and `409 concurrent_idempotent_requests`, waiting for `retry-after` when Cresca sends it and otherwise sleeping 1, 2 and 4 seconds plus jitter. Other 4xx responses are raised at once; a resend would be rejected the same way.
- **Raises a typed error.** A failed call returns a body such as `{"statusCode": 422, "name": "validation_error", "message": "..."}`. `Cresca::Error` keeps the HTTP status in `status` and the stable `name` in `code`. Rescue on the code, since message wording can change.

```ruby
# 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
```

`sleep` blocks the current thread, which is fine in a job or a script. In a web process, call the client from a background job instead. Using it:

```ruby
require "cgi"
require_relative "cresca"

sent = Cresca.post("/emails", {
  from: "Acme <hello@acme.com>",
  to: user.email,
  subject: "Welcome to Acme",
  html: "<p>Hi #{CGI.escapeHTML(user.first_name)}, your account is ready.</p>"
}, idempotency_key: "welcome/#{user.id}")

puts sent["id"]
```

`CGI.escapeHTML` keeps user data from changing your markup. To react to a particular failure, `rescue Cresca::Error => e` and branch on `e.code`, for example paging someone on `invalid_from_address`.

## Send a template with variables

Building HTML with interpolation or ERB gets tedious. Instead, design the email in Cresca's template editor, mark the values your code fills in with triple braces such as `{{{RESET_LINK}}}`, and publish. Your Ruby code then sends the template alias and a hash of variables. Sends always use the *published* version, so a draft can change without touching live email. Cresca HTML-escapes the values, so no `CGI.escapeHTML` is needed here. Leave out a variable that has no fallback and `Cresca::Error` is raised with code `validation_error` (status 422) naming it. See [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: reset_url }
  }
}, idempotency_key: "password-reset/#{reset_request.id}")
```

## Add attachments

Read the file with `File.binread` so Ruby doesn't apply any text encoding, then base64 it into the JSON. Each attachment needs `filename` and `content`, with `content_type` optional. A `content_id` lets you show an image inline via `<img src="cid:logo">`. You can attach up to 20 files and 7 MB in total per email. Executables such as .exe and .js are rejected, and URL attachments are not supported yet.

```ruby
pdf = File.binread("invoices/inv-2026-0042.pdf")

Cresca.post("/emails", {
  from: "Acme Billing <billing@acme.com>",
  to: customer.email,
  subject: "Your invoice INV-2026-0042",
  html: "<p>Thanks for your payment. Your invoice is attached.</p>",
  attachments: [{
    filename: "inv-2026-0042.pdf",
    content: [pdf].pack("m0"), # strict base64, no line breaks
    content_type: "application/pdf"
  }]
}, idempotency_key: "invoice/inv-2026-0042")
```

`[pdf].pack("m0")` is strict base64 (no line breaks) using only core Ruby. `Base64.strict_encode64` gives the same output, but since Ruby 3.4 `base64` is a bundled gem, so under Bundler you would have to add it to your Gemfile.

## Send a batch of up to 100 emails

`POST /emails/batch` takes an array of up to 100 emails, and `each_slice(100)` cuts your list into exactly that. An item accepts every single-send field apart from `attachments` and `scheduled_at`. Validation covers the whole array: one invalid item and nothing is sent, with the error message giving that item's zero-based index. On success, `result["data"]` lists the ids in the same order as your array. Each batch is one request against your rate limit, which is how you reach thousands of emails a minute.

```ruby
emails = users.map do |user|
  {
    from: "Acme <hello@acme.com>",
    to: user.email,
    subject: "Your weekly summary",
    html: render_summary(user)
  }
end

emails.each_slice(100).with_index do |chunk, index|
  result = Cresca.post("/emails/batch", chunk, idempotency_key: "weekly-summary/2026-10-27/#{index}")
  puts "Batch #{index}: #{result['data'].size} emails accepted"
end
```

`with_index` numbers the slices, and that number goes into the idempotency key. Keep `users` in a fixed order so a rerun produces the same slices.

## Send email from a Sidekiq job

Sidekiq retries a job that raises, with its own growing delay (up to 25 times by default), so a `Cresca::Error` on a 5xx that outlasts the client's four attempts will be picked up again later. Because the job passes the same `welcome/` key every time, a retry after a crash or timeout still results in one email. Pass the user id, not the user, since Sidekiq arguments must be simple JSON types.

```ruby
class WelcomeEmailJob
  include Sidekiq::Job

  def perform(user_id)
    user = User.find(user_id)
    Cresca.post("/emails", {
      to: user.email,
      template: { id: "welcome", variables: { NAME: user.first_name } }
    }, idempotency_key: "welcome/#{user.id}")
  end
end

WelcomeEmailJob.perform_async(user.id)
```

For errors that will never succeed, such as `invalid_from_address`, you may want to rescue `Cresca::Error` in `perform` and report it instead of letting Sidekiq retry 25 times.

## Net::SMTP, the mail gem or an email API?

Both `Net::SMTP` and the mail gem work well if you have an SMTP server. Note that `net-smtp` has been a bundled gem since Ruby 3.1, so Bundler apps need it in the Gemfile. An API skips the SMTP login, the TLS negotiation and the socket errors, gives you JSON errors with a stable `name`, and supports idempotency keys. Cresca has no SMTP relay yet, so the API is how you send. If you are in a Rails app, [send email with Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails) shows how to keep ActionMailer and deliver through Cresca.

## Errors to handle when you send email with Ruby

What the client does with each common error. The full reference is the [errors page](https://www.cresca.xyz/docs/errors).

| e.code | e.status | Cresca.post | Meaning |
| --- | --- | --- | --- |
| `invalid_from_address` | 403 | Raises immediately | The from address isn't an active sender on a verified domain |
| `validation_error` | 422 | Raises immediately | A bad field, or a missing template variable |
| `missing_required_field` | 422 | Raises immediately | No `to`, `from` or `subject`, and no template supplying them |
| `rate_limit_exceeded` | 429 | Sleeps for `retry-after`, retries | Too many requests per second for your plan |
| `monthly_quota_exceeded` | 429 | Raises immediately | This month's email allowance is used |
| `concurrent_idempotent_requests` | 409 | Retries after a short sleep | A request with the same key is still running |
| `application_error` | 5xx | Retries with backoff | A fault on Cresca's side |

Recipients on your suppression list (previous hard bounces, complaints and unsubscribes) are skipped, and the call still succeeds. See [suppression](https://www.cresca.xyz/docs/suppression).

## Check that the email was delivered

`200` means accepted, not delivered. Log `sent["id"]` or store it with the record that triggered the email. In the app, [Transactional](https://app.cresca.xyz/transactional) shows a timeline for every email. To check one from a terminal you need a full-access key, because sending keys cannot read logs:

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

`last_event` starts as `queued`, changes to `sent`, and settles on `delivered` or `bounced`. [Email lifecycle](https://www.cresca.xyz/docs/email-lifecycle) describes every status.

## Frequently asked questions

### Can I use Faraday or HTTParty instead of Net::HTTP?

Yes. Send the same JSON body and headers and keep the same rules: retry network errors, 429 rate\_limit\_exceeded and 5xx with an Idempotency-Key, and never retry other 4xx errors.

### Do I need the base64 gem?

Not for this code. Array#pack("m0") produces strict base64 in core Ruby. The base64 library became a bundled gem in Ruby 3.4, so Base64.strict\_encode64 under Bundler means adding it to your Gemfile.

### Is there an official Cresca gem?

No, and you don't need one. The API is plain HTTPS and JSON. The module above is a few dozen lines of standard-library Ruby you can copy into your project and own.

## 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) · [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) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

Every field of the Emails API, with cURL, is in the [send email API guide](https://www.cresca.xyz/blog/send-email-api). The [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) gives the wider picture, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) compares this approach with Net::SMTP-style sending.

## Start sending

Save the module as `cresca.rb`, export your key and run the basic example. **[Open a 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. Continue with the [quickstart](https://www.cresca.xyz/docs/quickstart) or the [API docs](https://www.cresca.xyz/docs).
