Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Ruby SDK

Use BillionSend from Ruby with the billionsend gem.

The billionsend gem is the BillionSend client for Ruby. It covers every operation of the API reference: sending, domains, contacts, broadcasts, templates, webhooks, inboxes with their threads and drafts, live inbox events and agent sign-up. The source is billionsend/billionsend-ruby on GitHub.

Install

Needs Ruby 3.1 or newer. The gem has no runtime dependencies: it uses net/http, json and openssl from the standard library.

gem install billionsend -v 0.1.0

In a Gemfile, gem "billionsend", "~> 0.1".

Send an email

require "billionsend"

client = BillionSend::Client.new # reads BILLIONSEND_API_KEY

sent = client.emails.send({
  from: "Acme <hello@acme.dev>",
  to: ["ana@example.com"],
  subject: "Welcome to Acme",
  html: "<p>Glad you are here.</p>"
}, idempotency_key: "welcome/ana")

puts sent["id"]

BillionSend::Client.new(api_key: "bs_...") takes the key directly; base_url:, timeout: (seconds per attempt, default 60), max_retries:, default_headers: and transport: (anything that answers call and open_stream like BillionSend::NetHTTPTransport, to send through your own HTTP stack) set the rest. BILLIONSEND_BASE_URL overrides the API URL.

Method names

Each operation is a method named after its id in the API reference, the dotted path as a chain of resources in snake_case: emails.send is client.emails.send, emails.receiving.attachments.list is client.emails.receiving.attachments.list, and agent.claimEmail is client.agent.claim_email. emails.metrics is client.emails.metrics.call, beside .links, .countries and .clients.

A method takes the path parameters in order, the request body as a Hash in braces, then the query and header parameters as keyword arguments, and last extra_headers: and timeout:. Bodies take symbol or string keys; answers are Hashes with string keys and the API’s own field names (sent["id"]), so the API reference describes them field for field. emails, inboxes and broadcasts have a send method, which hides Object#send on them: reach their methods dynamically with public_send.

Idempotency and retries

The eight sending operations (emails.send, emails.batch, received-mail replies and forwards, inboxes.send, inboxes.drafts.send, thread replies and forwards) always send an Idempotency-Key. Without idempotency_key:, each call makes one up that its retries reuse, so a retry after a timeout never sends twice; your own key also makes a repeat from another process safe.

Failures worth retrying are retried twice by default: 429, 5xx, timeouts, network errors, and the 409 concurrent_idempotent_requests answered while the first attempt with the same key is still running. Only requests safe to repeat are retried: GET, PUT, DELETE and any request carrying an Idempotency-Key, as every sending operation does. The client waits as Retry-After asks, and raises at once when it asks for more than a minute; otherwise it backs off exponentially from 0.5 s to 8 s, less up to a quarter at random. Every method takes timeout: and extra_headers: for that call, and the sending ones idempotency_key:; max_retries: is set on the client.

Errors

A failed call raises ValidationError (400, 422), AuthenticationError (401, or no key configured), PermissionDeniedError (403), NotFoundError (404), ConflictError (409), RateLimitError (429, with retry_after in seconds), APIError (5xx), APIConnectionError (no answer) or APITimeoutError (the attempt timed out, a kind of APIConnectionError). All are in the BillionSend module and extend BillionSend::Error, raised as itself for any other status, with status_code, name (the API’s error name), message and request_id, the answer’s x-request-id, which is the request’s id on the dashboard’s Logs page.

begin
  puts client.emails.get(id)["subject"]
rescue BillionSend::NotFoundError
  # no such email
rescue BillionSend::Error => e
  warn "#{e.status_code} #{e.name}: #{e.message} (request #{e.request_id})"
end

Lists

List methods return one page. Every cursor list also has a ..._all method (search_all for thread search) that returns a lazy Enumerator, fetching the next pages as it goes, backward when before: is set:

client.contacts.list_all(limit: 100).each do |contact|
  puts contact["email"]
end

An agent’s inbox

Wait for new mail on the event stream and reply in its thread:

stream = client.inboxes.events.stream_inbox("support@acme.dev", types: "inbox.email.received")
begin
  stream.each do |event|
    next if event.is_a?(BillionSend::StreamGapEvent) # events may be missing: read the threads again

    data = event.data["data"]
    client.inboxes.threads.emails.reply(
      event.data["inbox_id"], data["thread_id"], data["email_id"],
      { text: "Thanks, we are on it." },
      idempotency_key: "reply/#{data["email_id"]}"
    )
  end
ensure
  stream.close
end

The stream reconnects with Last-Event-ID when the connection drops and replays what it missed; keep stream.last_event_id and pass it back as last_event_id: to resume after a restart. A StreamGapEvent comes once when the stream resumes from more than 24 hours back. max_reconnects: (default 5 failed reconnects in a row; 0 gives up at the first) tunes reconnecting, which waits a second, or what the server’s retry field asks, before each attempt. One inbox’s stream ends after that inbox is deleted or expires; client.inboxes.events.stream follows every inbox the key can read.

Verify webhooks

BillionSend.verify_webhook checks a webhook delivery’s signature and timestamp with the endpoint’s whsec_ secret and returns the parsed event. Pass the body exactly as it arrived; header names match in any case:

# config.ru
require "billionsend"

SECRET = ENV.fetch("BILLIONSEND_WEBHOOK_SECRET")
NAMES = %w[webhook-id webhook-timestamp webhook-signature].freeze

app = lambda do |env|
  headers = NAMES.to_h { |name| [name, env["HTTP_#{name.upcase.tr("-", "_")}"]] }
  event = BillionSend.verify_webhook(env["rack.input"].read, headers, SECRET)
  warn event["type"]
  [204, {}, []]
rescue BillionSend::WebhookVerificationError
  [400, {}, ["bad signature"]]
end

run app

A delivery older than five minutes is refused, and during a secret rotation either secret verifies.

Was this page helpful?