Skip to content
Tinbox

tutorials

Send your first email with the tinbox/cf library

November 25, 2026

#cloudflare-workers#tinbox-cf#transactional-email#sdk#tutorial
Interlocking email tool modules illustrate a composable developer interface.

You have a Worker that needs to send one email: a receipt, a magic link, a notification. You do not want a SaaS SDK, a second vendor dashboard, or a per-email bill. You want a fetch you control.

A deployed Tinbox is one Cloudflare Worker that, among everything else, exposes a Resend-style sending API at /api/send on your own account. This post is the narrow recipe: get a single transactional email out the door from a Worker, with the smallest amount of code that is still honest about what is happening.

How do I send an email with Tinbox?

You POST to the /api/send/emails endpoint with a tbx_ API key — the @tinbox/sdk client (or a plain fetch) does the call. There is no separate SaaS service in the path: the endpoint runs in your Worker, writes to your D1, and dispatches through Cloudflare's send_email binding. Behind that one call the endpoint de-duplicates recipients against your suppression list, records a ledger row per recipient keyed by your idempotency key, and hands the assembled MIME to Cloudflare for delivery. External apps can now submit directly to Cloudflare over authenticated SMTP, but that path bypasses the Tinbox ledger; Workers should use the binding or HTTPS path described here.

So the recipe is: a deployed Tinbox (the endpoint), plus a call to /api/send/emails from wherever you send (your app, another Worker, a cron job). If you already ran npx tinbox init, you have the endpoint — skip to sending from an existing Worker. If you have not deployed yet, the npx tinbox init walkthrough stands it up, including the createWorker() entry and the D1/R2/send_email bindings the send path needs.

Local dev note: before your domain's SPF/DKIM are verified, or while EMAIL is unbound in local dev, the dispatcher logs instead of delivering — by design, so development never bounces real mail. The send is recorded in D1 but nothing leaves Cloudflare. Bind EMAIL and verify your domain (see the SPF, DKIM, and DMARC setup) before expecting real delivery.

How do I mint a tbx_ API key?

Open your deployment's console, go to Settings then API keys, and create a key with the api:send scope. Keys are prefixed tbx_ and are sent as a bearer token. Treat them like any other secret: store the key in wrangler secret put, not in vars.

npx wrangler secret put TINBOX_API_KEY
# paste the tbx_… value when prompted

The send endpoint authorizes by checking the Authorization: Bearer tbx_… header against the keys in your D1. No key, or a key without api:send, gets a 401.

How do I send from an existing Worker?

Bind the send Worker as a service binding (or use its public URL) and POST to /api/send/emails with your tbx_ key. You have two ergonomic options: the @tinbox/sdk client, or a plain fetch. Both hit the same route.

Option A: the @tinbox/sdk client

@tinbox/sdk is a dependency-free fetch wrapper. Its baseUrl is your host plus the send mount, /api/send:

// src/worker-that-sends.ts
import { Tinbox } from "@tinbox/sdk";

interface Env {
  TINBOX_API_KEY: string;
}

export default {
  async fetch(req: Request, env: Env): Promise<Response> {
    const tinbox = new Tinbox({
      apiKey: env.TINBOX_API_KEY,
      baseUrl: "https://acme.com/api/send",
    });

    const result = await tinbox.emails.send({
      from: "Acme <hello@acme.com>",
      to: "ada@example.com",
      subject: "Your receipt",
      html: "<p>Thanks for your order. Total: $42.</p>",
      idempotency_key: "order-1042-receipt",
    });

    return Response.json(result);
  },
};

The response is the same wire shape whether you use the SDK or raw fetch:

{
  "id": "order-1042-receipt",
  "ok": true,
  "message_id": "<a1b2c3@acme.com>",
  "recipients": [
    { "recipient": "ada@example.com", "status": "sent", "message_id": "<a1b2c3@acme.com>" }
  ],
  "suppressed": []
}

Read ok carefully: it is true only if every recipient ended sent or duplicate. A multi-recipient send where one address is suppressed and one is delivered returns ok: false with details in recipients and suppressed. Do not treat a 200 as "all delivered"; treat the recipients array as the source of truth.

Option B: a plain fetch (no SDK)

If you would rather not add a dependency, the SDK is a thin convenience and you can skip it. The endpoint is just JSON over HTTPS:

const res = await fetch("https://acme.com/api/send/emails", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${env.TINBOX_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": "order-1042-receipt",
  },
  body: JSON.stringify({
    from: "Acme <hello@acme.com>",
    to: "ada@example.com",
    subject: "Your receipt",
    html: "<p>Thanks for your order. Total: $42.</p>",
  }),
});

if (!res.ok) {
  // 401 = bad/absent key, 422 = invalid payload (e.g. a non-X- header)
  throw new Error(`send failed: ${res.status} ${await res.text()}`);
}
const result = await res.json();

Two failure modes worth knowing: a 401 means the tbx_ key is missing or lacks api:send, and a 422 means the payload was rejected. The most common 422 is a custom header that is not an X-* header: the endpoint only accepts X- prefixed extra headers and rejects the rest, to keep you from injecting envelope-level fields.

Service binding instead of a public URL

If both Workers live on the same account, skip the public hostname and bind the send Worker as a service. Add it to the caller's wrangler.jsonc:

{
  "services": [
    { "binding": "TINBOX", "service": "tinbox-acme" }
  ]
}

Then the baseUrl becomes a binding-relative URL and the request stays on Cloudflare's internal network (lower latency, no public round-trip):

const res = await env.TINBOX.fetch(
  new Request("https://internal/api/send/emails", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${env.TINBOX_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      from: "Acme <hello@acme.com>",
      to: "ada@example.com",
      subject: "Your receipt",
      html: "<p>Thanks for your order.</p>",
    }),
  }),
);

The host in the Request URL is ignored for a service binding (the binding routes it), so any placeholder host works. You still send the tbx_ key, because the send endpoint authorizes the call regardless of how it arrived.

How do I check that an email actually sent?

POST returns the immediate per-recipient outcome, and GET /api/send/emails/:id returns the full delivery status and event timeline later. The id is your idempotency key (or a derived one if you omitted it):

const status = await tinbox.emails.get("order-1042-receipt");
// → { id, message_id, status: "sent" | "pending" | "failed", recipients: [...], events: [...] }

The events array carries the lifecycle (queued, delivered, bounced, complained) as your dispatcher reports it. For handling the unhappy paths (hard bounces, complaints feeding the suppression list) the mechanics are the same ledger, read back over time.

When should I batch instead of looping?

Use emails.batch() when you have many distinct messages to send in one call, rather than awaiting send() in a loop. Each item gets its own result, and a single bad item does not fail the others:

const { results } = await tinbox.emails.batch([
  { from: "hello@acme.com", to: "ada@example.com", subject: "Hi Ada", html: "<p>…</p>" },
  { from: "hello@acme.com", to: "grace@example.com", subject: "Hi Grace", html: "<p>…</p>" },
]);
// results[i] is either a send outcome with { index, ok, recipients } or { index, error }

Looping await send() works and is fine for a handful, but it is N round-trips. Batch is one. This is the same N+1 instinct you would apply to a database, applied to your own send API.

The honest caveats

A few things to keep accurate in your head:

  • One brand and domain per deployment. Multi-domain-per-instance is designed but not built. You run many tenants per Cloudflare account by doing separate tinbox init deploys, each tinbox-<brand>-*, not by serving many domains from one Worker.
  • Delivery still depends on your DNS. tinbox/cf gives you the sending plumbing; SPF, DKIM, and DMARC on your domain decide whether the mail lands. The logging-dispatcher fallback in local dev means a "successful" send in development is not proof of delivery.
  • The license is honor-system. If you set TINBOX_LICENSE_KEY, an unlicensed instance nags but blocks nothing. Sending is not gated on a license.

Where to go from here

That is the whole recipe: deploy once, mint a key, POST to /api/send/emails. The send call is exactly the tinbox.emails.send({ from, to, subject, html }) above, on your own Cloudflare account with no per-email pricing in the loop.

For the surrounding pieces see what transactional email actually costs, the self-hosted Resend alternative, and the SPF, DKIM, and DMARC setup that decides whether your mail lands. For the fuller API surface beyond a single send — attachments, batch, inbound parsing, and querying your inbox — see working with tinbox/cf in code. To meet the rest of the stack, start at the Tinbox overview.

Haven't deployed yet? npx tinbox init <domain> — the walkthrough. The send API, key scopes, and wire shapes are in the docs under the sending reference.

Frequently asked questions

How do I send a transactional email from my own Worker with Tinbox?

Your deployment exposes a Resend-style sending API at /api/send. You send by POSTing to /api/send/emails with a tbx_ API key, either through the @tinbox/sdk Tinbox client or a plain fetch. From a second Worker on the same account, reach it over a service binding instead of the public URL.

Do I need a separate SaaS account or SDK to send?

No. The send endpoint runs inside your own Tinbox Worker, backed by your own D1 database. The @tinbox/sdk client is a dependency-free fetch wrapper, and you can skip it entirely and call the HTTP API directly.

What does the send response look like?

POST /api/send/emails returns JSON with an id (the idempotency correlation key), an ok boolean that is true only when every recipient ended sent or duplicate, a message_id, a recipients array of per-recipient outcomes, and a suppressed array for addresses dropped because they are on your suppression list.

Can Cloudflare Workers send email over SMTP instead?

Not through Cloudflare's SMTP endpoint. Workers have connect() for outbound TCP, but port 25 and Cloudflare IP ranges are blocked; smtp.mx.cloudflare.net is therefore not a Worker transport. External applications can submit transactional mail there on implicit-TLS port 465. Tinbox uses HTTPS or the native binding so every send still crosses its authorization and idempotency ledger.

How do I make sends idempotent so retries do not double-send?

Pass idempotency_key in the request body. A repeated key returns the original outcome with each recipient marked duplicate instead of dispatching again, which is safe for queue retries and cron jobs.