Guide · REST API · Ruby

Send email with Ruby

To send email with Ruby, POST a JSON body to tinyRelay's /email/campaign endpoint with Net::HTTP from the standard library, putting your API key in the X-RELAY-ACCESS-TOKEN header. One request can greet every recipient by name.

ONE REQUEST · THREE EMAILS
{ "email" => "ann@example.com",
  "attributes" => { "FIRST_NAME" => "Ann" },
  "metadata" => { "user_id" => "u_1042" } }
{ "email" => "bob@example.com",
  "attributes" => { "FIRST_NAME" => "Bob" },
  "metadata" => { "user_id" => "u_2077" } }
{ "email" => "chen@example.com",
  "attributes" => { "FIRST_NAME" => "Chen" },
  "metadata" => { "user_id" => "u_3150" } }

Illustrative. attributes render into the email; metadata comes back on webhooks.

Endpoint
POST /email/campaign
Auth header
X-RELAY-ACCESS-TOKEN
Success
202 · requestId
Library
Net::HTTP (stdlib)

Before you start

Accounts are set up with you during onboarding. For the DKIM record and the rest of your sending setup, see transactional email deliverability.

No package to install. tinyRelay works with any language that can make HTTP requests. Everything below uses a standard HTTP client.

Send email from Ruby, step by step

The example sends a sign-up confirmation email. The second tab runs the same call from a Rails background job.

1. Store your API key

Keep the key out of your code. Set it as an environment variable on the server that calls tinyRelay.

export TINYRELAY_API_KEY="your-api-key"
$env:TINYRELAY_API_KEY = "your-api-key"

2. Build the request body

Build a hash with string keys that match the JSON field names. JSON.generate turns it into the request body.

email.rbCopy
email = {
  "subject" => "Confirm your Acme email address",
  "body" => "<p>Hi [FIRST_NAME], confirm your address to finish signing up.</p>",
  "sender" => {
    "from" => { "name" => "Acme", "email" => "no-reply@acme.com" },
    "replyTo" => { "name" => "Acme Support", "email" => "support@acme.com" }
  },
  "recipients" => {
    "to" => [
      {
        "name" => "Ann Lee",
        "email" => "ann@example.com",
        "attributes" => { "FIRST_NAME" => "Ann" }
      }
    ]
  },
  "metadata" => { "user_id" => "u_1042", "flow" => "signup_confirm" }
}

3. POST it to /email/campaign

TinyRelay.send_email returns the requestId and raises on anything other than 202. In Rails, call it from a job so a slow network never holds up a web request.

# lib/tiny_relay.rb
require "json"
require "net/http"
require "uri"

module TinyRelay
  SEND_URI = URI("https://api.tinyemail.com/v1/relay/email/campaign")

  def self.send_email(email)
    request = Net::HTTP::Post.new(SEND_URI)
    request["Content-Type"] = "application/json"
    request["X-RELAY-ACCESS-TOKEN"] = ENV.fetch("TINYRELAY_API_KEY")
    request.body = JSON.generate(email)

    response = Net::HTTP.start(SEND_URI.host, SEND_URI.port,
                               use_ssl: true, open_timeout: 5, read_timeout: 10) do |http|
      http.request(request)
    end

    raise "tinyRelay #{response.code}: #{response.body}" unless response.code == "202"

    JSON.parse(response.body).fetch("requestId")
  end
end
# app/jobs/send_confirmation_email_job.rb
class SendConfirmationEmailJob < ApplicationJob
  queue_as :default

  def perform(user_id)
    user = User.find(user_id)
    TinyRelay.send_email({
      "subject" => "Confirm your Acme email address",
      "body" => "<p>Hi [FIRST_NAME], confirm your address to finish signing up.</p>",
      "sender" => { "from" => { "name" => "Acme", "email" => "no-reply@acme.com" } },
      "recipients" => {
        "to" => [{ "email" => user.email, "attributes" => { "FIRST_NAME" => user.first_name } }]
      },
      "metadata" => { "user_id" => user.id.to_s, "flow" => "signup_confirm" }
    })
  end
end

# After sign-up:
SendConfirmationEmailJob.perform_later(user.id)

Base URL from current site samples; confirm in the docs.

Net::HTTP or Action Mailer?

Use this REST approach when you want per-recipient metadata echoed on every webhook, or one request for many recipients. If your Rails app already sends through Action Mailer, you can point it at the tinyRelay SMTP relay instead: see Rails Action Mailer SMTP settings.

4. Check for a 202

Net::HTTP returns the status as a string, so compare response.code == "202". The parsed body holds the requestId.

The 202 response

A request that passes validation returns 202. That means tinyRelay accepted the send; what happens to each email afterwards arrives as webhook events.

202 Accepted · response bodyCopy
{
  "requestId": "833c5151-5a98-4bad-a30f-7cc816352b7a",
  "message": "SUCCESS"
}
  • requestId identifies this send. Store it next to your own record.
  • If you did not set campaignId, the requestId is used as the campaign ID, and every webhook event for the send carries it.
  • A 202 is not delivery. Watch for DELIVERED or BOUNCED events.

Personalize many recipients in one Ruby request

Map users into recipients.to. Use braces for the block so it binds to map, not to send_email.

batch.rbCopy
TinyRelay.send_email({
  "subject" => "Confirm your Acme email address",
  "body" => "<p>Hi [FIRST_NAME], confirm your address to finish signing up.</p>",
  "sender" => { "from" => { "name" => "Acme", "email" => "no-reply@acme.com" } },
  "metadata" => { "tenant_id" => "acme", "flow" => "signup_confirm" },
  "recipients" => {
    "to" => users.map { |user|
      {
        "email" => user.email,
        "attributes" => { "FIRST_NAME" => user.first_name },
        "metadata" => { "user_id" => user.id.to_s }
      }
    }
  }
})

The rules, from the Send Email docs:

10keys
Merged metadata map

Request-level and recipient-level maps merge. The cap is on the merged map.

Over412 · nothing sent
500recipients
With their own metadata

At most 500 recipients in one request may carry their own metadata.

Over412 · nothing sent
64chars
Key length

Each metadata key can be up to 64 characters.

Applies toevery key
256chars
Value length

Values up to 256 characters: flat strings, numbers or booleans.

Valuesflat only

attributes are merge tags rendered into the body, such as [FIRST_NAME], and never echoed on webhooks. metadata is never rendered into the email and is always echoed on webhooks.

"attributes": { "FIRST_NAME": "Ann" }     // in the email: "Hi Ann"
"metadata":   { "user_id": "u_1042" }    // on every webhook event

Request-level and recipient-level maps merge, and the recipient's keys win.

// request    { "tenant_id": "acme", "plan": "pro" }
// recipient  { "plan": "team" }
// merged     { "tenant_id": "acme", "plan": "team" }

Values must be flat strings, numbers or booleans.

{ "order_id": "SO-1", "total": 42, "gift": true }   // flat: fine
{ "order": { "id": "SO-1" } }                       // nested object: not flat

Metadata is scoped to campaignId. Reusing a campaignId across batches replaces the earlier metadata, so use a unique one per batch or leave it out.

"campaignId": "password_reset_batch_0142"   // unique per batch
// or leave it out: the requestId is used as the campaign ID

Handle delivery webhooks

tinyRelay posts an event to your webhook endpoint for each thing that happens to an email. There are seven event types:

POST → your webhook endpoint · 7 event typessigned via Svix
  1. SENDSent to the receiving server
  2. DELIVEREDEmail delivered
  3. BOUNCEDHARD_BOUNCED or SOFT_BOUNCED · adds bounceCategory
  4. OPENOpened by the recipient
  5. CLICKA tracked link was clicked · adds url
  6. UNSUBSCRIBEUnsubscribe link clicked
  7. SPAMMarked as spam

SEND: the email was sent. Apps usually mark the message as sent against their record.

Each event carries eventType, receiver, requestId, campaignId and your merged metadata. BOUNCED events add bounceCategory, and CLICK events add the url that was clicked.

Verify, then deduplicate. Webhooks are signed with svix-id, svix-timestamp and svix-signature headers and delivered at least once, so verify each request and deduplicate on svix-id.

Read email webhooks and delivery events, then verify webhook signatures. Bounce categories are explained in the email bounce codes reference; field-level detail is in the webhook docs.

Troubleshooting

The Send Email endpoint documents four error statuses. Match the status you get to the row below.

StatusMeaningWhat to check
400MeaningBad RequestWhat to checkThe body failed validation. The response carries a message field; read it, fix the field it names and resend.
401MeaningAPI key missing or invalidWhat to checkCheck the header is named X-RELAY-ACCESS-TOKEN and holds the key issued at onboarding. If the key is right, confirm the server you are calling from has an IP on your allowlist.
405MeaningMethod Not AllowedWhat to checkSend a POST to /email/campaign. Other methods are refused.
412MeaningMetadata limits brokenWhat to checkThe merged metadata map has more than 10 keys, or more than 500 recipients carry their own metadata. Nothing is sent; trim the metadata and resend.

Full error schemas are in the Send Email API reference.

FAQ

Is there a tinyRelay gem for Ruby?

No. tinyRelay has no package to install. Net::HTTP and JSON from the Ruby standard library are enough.

Net::HTTP returns the status code as a string, so response.code == 202 with an integer would never match.

Yes, over SMTP. Point Action Mailer at the tinyRelay SMTP relay with the credentials issued at onboarding. Use the REST API when you need per-recipient metadata in one request.

In an environment variable or Rails credentials, read on the server. Never put it in JavaScript sent to the browser or in your repository.

Next steps

Sources

Get started

Send transactional email with a service that reports back.

SMTP relay or REST API, standalone or alongside tinyEmail. Tell us what you send and our team sets you up.