By language

Receive email in Ruby

Receive and process inbound email in Ruby with Rails or Sinatra: verify Inboundr's signed webhook and process each message in a background job.

This guide receives every email sent to your domain in Rails or Sinatra, verifies it came from Inboundr, and processes it in the background. It uses only openssl from the standard library. Ruby 3.1 or later.

Before you start#

  • An address to receive on. Your account comes with an instant domain such as amber-falcon-4821.inboundr.email, so any address on it works without DNS setup. A verified domain of your own works the same way.
  • An API key, from API keys in the console:
    bash
    export INBOUNDR_API_KEY="inb_xxxxxxxxxxxxxxxxxxxxxxxx"
  • A public HTTPS URL for your handler. Inboundr only delivers to public addresses, so while developing, expose your local port with a tunnel:
    bash
    ngrok http 3000
    # or: cloudflared tunnel --url http://localhost:3000

1. Create an endpoint and route mail to it#

An endpoint is the URL Inboundr POSTs each email to. Create one pointing at your tunnel:

bash
curl https://inboundr.net/api/v1/endpoints \
  -H "Authorization: Bearer $INBOUNDR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "name": "Local handler", "url": "https://<your-tunnel>/webhooks/inboundr" }'

The response includes a secret (whsec_…). It's shown only once, so store it next to your API key:

bash
export INBOUNDR_WEBHOOK_SECRET="whsec_xxxxxxxxxxxxxxxxxxxxxxxx"

Then send the domain's mail to the endpoint. Find the domain's ID (the instant domain is the one with "managed": true) and set it as the catch-all:

bash
curl https://inboundr.net/api/v1/domains \
  -H "Authorization: Bearer $INBOUNDR_API_KEY"

curl -X PATCH https://inboundr.net/api/v1/domains/dom_123 \
  -H "Authorization: Bearer $INBOUNDR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "catchAllEndpointIds": ["ep_123"] }'

To route a single address instead, see addresses.

2. Write the handler#

The handler gets the parsed message as JSON: from, to, recipients, subject, text, html, attachment metadata and the spam, SPF and DKIM verdicts. See the full payload. The signature check:

inboundr_signature.rb
require "openssl"

module InboundrSignature
  # Checks X-Inboundr-Signature: t=<unix>,v1=<hex HMAC-SHA256 of "t.body">.
  def self.valid?(raw_body, header, secret)
    return false if header.nil? || header.empty?

    # Segments without "=" are skipped, so junk is refused rather than raising.
    parts = header.split(",").filter_map { |kv| kv.split("=", 2) if kv.include?("=") }.to_h
    t = parts["t"].to_s
    # Reject old deliveries so a captured request can't be replayed.
    return false unless t.match?(/\A\d+\z/) && (Time.now.to_i - t.to_i).abs <= 300

    expected = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{t}.#{raw_body}")
    OpenSSL.secure_compare(expected, parts["v1"].to_s)
  end
end

Then the route:

Rails
# config/routes.rb
#   post "/webhooks/inboundr", to: "inboundr_webhooks#create"

class InboundrWebhooksController < ActionController::API
  def create
    raw = request.raw_post # raw bytes, before any JSON parsing
    header = request.headers["X-Inboundr-Signature"]
    unless InboundrSignature.valid?(raw, header, ENV.fetch("INBOUNDR_WEBHOOK_SECRET"))
      return head :unauthorized
    end

    email = JSON.parse(raw).fetch("email")
    # Answer now, work later: slow handlers time out and get retried.
    ProcessInboundEmailJob.perform_later(
      email, request.headers["X-Inboundr-Delivery-Id"]
    )
    head :ok
  end
end

Processing the message, from the job or the thread:

process_email.rb
require "net/http"

def process_email(email)
  puts "#{email["from"]} -> #{email["recipients"].join(", ")}: #{email["subject"]}"

  Dir.mkdir("attachments") unless Dir.exist?("attachments")
  email["attachments"].each_with_index do |attachment, i|
    next if attachment["downloadUrl"].nil? # not stored on this plan

    uri = URI(attachment["downloadUrl"])
    req = Net::HTTP::Get.new(uri)
    req["Authorization"] = "Bearer #{ENV.fetch("INBOUNDR_API_KEY")}"
    res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }
    next unless res.is_a?(Net::HTTPSuccess)

    # Inline images often have no filename, and two can share one, so the
    # index keeps them apart. File.basename: never trust a sender's name as a path.
    name = File.basename(attachment["filename"] || "attachment-#{i}")
    path = File.join("attachments", "#{email["id"]}-#{i}-#{name}")
    File.binwrite(path, res.body)
  end
end

In the Rails job, store the delivery ID with a unique index and return early when it's already there: retries keep their X-Inboundr-Delivery-Id.

3. Test it#

Send a sample delivery. It's signed with your endpoint's real secret, so it also tests your signature check:

bash
curl -X POST https://inboundr.net/api/v1/endpoints/ep_123/test \
  -H "Authorization: Bearer $INBOUNDR_API_KEY"

"ok": true means your handler answered with a 2xx. A 401 in status means the signature didn't match: see troubleshooting.

Then send a real email, with an attachment, from your own mailbox to any address on your domain, such as test@amber-falcon-4821.inboundr.email. It reaches your handler within seconds.

Read mail without a server#

Webhooks need a public URL. For scripts and rake tasks, read the inbox on demand instead. Mail is stored either way:

read_inbox.rb
require "json"
require "net/http"

uri = URI("https://inboundr.net/api/v1/emails?direction=inbound&limit=20")
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{ENV.fetch("INBOUNDR_API_KEY")}"
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) { |http| http.request(req) }

JSON.parse(res.body)["data"].each do |email|
  puts "#{email["receivedAt"]} #{email["fromAddress"]} #{email["subject"]}"
end

See the emails API for filters and pagination.

Troubleshooting#

  • Every delivery fails the signature check. The HMAC is computed over the exact bytes sent. Read the raw body before any JSON parsing, and don't re-serialize it. Also check you're using the endpoint's whsec_… secret, not your inb_ API key.
  • Deliveries time out. Your handler has 30 seconds by default. Acknowledge first, then do slow work (AI calls, downloads, database writes) in the background.
  • The same email arrives twice. A delivery is retried when your handler doesn't answer 2xx in time, and a retry keeps its X-Inboundr-Delivery-Id. Store handled IDs and skip repeats.
  • The body is empty. Some hosts drop request bodies. Every delivery also carries the email's ID with its own signature, so you can fetch it instead: see when the body is missing.
  • Nothing arrives. Check the email under Emails in the console. If it's there, open its delivery to see your handler's response. If it isn't, the message never reached Inboundr: check the address and, for your own domain, its MX record.

Next steps#