Skip to main content
The official mailkube Ruby SDK wraps the whole send surface behind keyword arguments and typed response models. It requires Ruby 3.4+ and has zero runtime dependencies. The standard library covers everything. That is deliberate: this gem is installed into other people’s applications, where every dependency is a version conflict waiting to happen.

Install

Get your API key

Create a key for a verified domain in the dashboard. The key is a string that starts with mk_. See Authentication for how to send it and keep it safe.

Send your first email

Configure the client

Pass the key explicitly with api_key:, or omit it and let the client read MAILKUBE_API_KEY:
If you are building something on top of this gem, such as a CLI, an internal service, or a framework integration, set user_agent_suffix: to your own name/version. It is appended after the SDK’s own token, so both are visible: mailkube-ruby/1.3.0 my-cli/1.0.0. The API requires a User-Agent on every request; the gem already sends one, and this identifies your layer within it. A value containing CR or LF is ignored. A header value that could split the request stays out of the request entirely, and quietly repairing it would hide the bug. Pass your own http: adapter to route through a proxy, add instrumentation, or drive the client from a test. Anything responding to #call(method:, url:, headers:, body:) and returning a Mailkube::HttpResponse qualifies.
There are deliberately no built-in retries. A RateLimitError carries retry_after and a ServerError is safe to retry with backoff, so the calling application decides.
Your API key can send email on your behalf. Keep it server-side, injected from a secrets manager or environment variable. Never ship it in a desktop application or a public repository.

The response

A successful send returns a Mailkube::Email with two identifiers:
Use email.id to correlate the message with webhook events. Use email.message_id in the In-Reply-To and References headers of a follow-up so replies thread correctly.

Recipients, content and attachments

to:, cc: and bcc: each accept a single address or an array of them. Supply html:, text:, or both. At least one is required for a raw send. Set reply_to: to route replies elsewhere. To send a saved template instead, pass template_id: (and optional template_version:) with a variables: hash.
content is raw bytes; the gem base64-encodes them for you.
Tags are denormalized onto the sending log for filtering, export and dashboards, and they ride along on delivery webhooks. Tag values are not encrypted. Never put personal data in one.

Idempotent sends

Set an idempotency key on anything you might retry. The API replays the original response and the message goes out once:
Reusing a key with a different payload raises Mailkube::ConflictError. See Idempotency for the full semantics.

Scheduled sends

Pass scheduled_at: to defer the send. A Time is rendered to ISO 8601 for you; a string is passed through untouched and must already carry an offset. The instant must be in the future and within your plan’s scheduling horizon.

Managing what is scheduled

The content of a scheduled email is immutable; only its due time and batch can change. List with status:, batch_id:, scheduled_at_gte:, scheduled_at_lte: and page:. An omitted filter is never sent:
For every page, use iter_all. It returns a lazy Enumerator, follows the server’s next link, and makes no request until you iterate it:
Only scheduled, canceled and failed can be listed. A sent email has left the collection; filtering on status: "sent" is rejected as a validation error. recipients on a listed email is a summary string ("[email protected] +2"), not an array; the full recipient list stays server-side. Group scheduled sends under a batch_id: and move or cancel them as a unit:
An unknown batch is a no-op reporting canceled_count: 0.

Your API key

client.credential.info returns the key the client authenticates with: its domain, organization, source-IP allowlist, plan and send-quota usage.
The key is checked exactly as a send checks it, so one call confirms a key works before your first send. A key that cannot send raises Mailkube::AuthenticationError with the error name invalid_api_key, and Checking a key lists the causes. Each call counts as a use of the key, and plan and quota figures can be up to 30 seconds old. plan is nil when the organization has no subscription. A plan without a daily limit lists emails_per_month only, and remaining counts recipients, not messages. The call has a rate limit of its own for each key. The client keeps the key it was constructed with. To use another key, construct another client.

Handling errors

Every error descends from Mailkube::Error, so rescue the category you care about:
The categories are BadRequestError (400), AuthenticationError (403), NotFoundError (404), ConflictError (409), InvalidRequestError (422), RateLimitError (429) and ServerError (5xx), all under APIError. A transport failure raises ConnectionError, deliberately outside the APIError tree. It carries no error_name, because the server never answered. Branch on error_name; the human-readable message is free to change. Mailkube::ErrorName lists the documented values for discoverability, but the set stays open: error_name stays a plain String, and a value this release has never heard of is reported verbatim. See Errors for what each one means. Quote request_id when reporting a failure to support. It is the only value that lets support find your exact call in the server-side logs.

Receiving webhooks

Mailkube::Webhooks.verify checks the signature over the raw request body and returns a typed event. It needs no client instance and no HTTP, and drops into any framework’s handler:
Verify against the raw received bytes, read from the request body before anything parses it. JSON round-tripping reorders keys and normalizes whitespace, and the signature will not match. The gem accepts any header mapping: a plain Hash, Rack’s CGI env as above, or Rails’ request.headers.
On Rails, the mailkube-rails gem ships a mountable receiver so you rarely write this handler yourself; see Ruby on Rails. verify applies a 300-second freshness window on X-Webhook-Ts, which is what rejects a replayed delivery. Widen or narrow it with tolerance:. Mailkube::Webhooks.verify_signature is the signature check alone, if you want to parse the body yourself. Typed classes live under Mailkube::Events for email.sent, email.delivered, email.bounced, email.delivery_delayed, email.suppressed, email.scheduled, email.failed, email.opened, email.clicked, domain.status and webhook.status. Two guarantees hold for every released version, which is what keeps a platform change from breaking a running receiver: an unknown event type parses as UnknownEvent rather than raising, and unknown fields are preserved at every nesting depth. event[...] and event.data[...] reach anything this release does not model, and event.to_h round-trips to exactly what the server sent. X-Webhook-Id is stable across retries. Deduplicate on it before acting. See Webhooks for the full event catalog.
When you create an endpoint, or re-point an existing one, mailkube probes it with GET <url>?hub.mode=subscribe&hub.challenge=<token> and persists it only if the body echoes that token verbatim with a 200. Mount your route on GET as well as POST. Skip this and no event is ever delivered.

Signing, for your tests

Production code verifies; it never signs. Mailkube::Webhooks.sign is the other half, for building a request your handler will accept without waiting on a real delivery:
It computes the HMAC exactly as verify checks it, so a fixture built this way cannot drift from the verifier. It takes the timestamp you give it and does not judge its freshness. Pass a stale one to assert that your handler rejects a replay.

Logging

Silent by default. Turn it on with any object responding to #write:
Or set MAILKUBE_LOG. It holds a level, not an on/off flag: MAILKUBE_LOG=debug turns the gem on, and anything more selective silences it. The gem emits one class of record, the request/response trace, and that record is debug-level. An unrecognized value leaves logging off. This is read at require time. The Authorization and Idempotency-Key headers are redacted from every line, and no recipient address, subject or body is ever written. The response line carries the server’s request id when one was sent.

Concurrency

Create one client and reuse it. It is frozen after construction and safe to share across threads, and across fibers where your application has installed a scheduler. Ruby releases the GVL around socket I/O, so plain threads give you real HTTP concurrency with no setup. Each request opens its own connection, because sharing one Net::HTTP across callers fails without raising: two callers interleave on one socket, and one receives the other’s response body. If you want pooling, inject an http: adapter that pools, and make it safe under threads and under a fiber scheduler.
RBS signatures ship in the gem’s sig/, so Steep and RBS-aware editors type your calls without extra setup.

Next steps

Webhooks

Every event type, its payload, and the signing scheme.

API reference

Every field, error code, and rate limit for the send endpoint.