tutorials
Working with tinbox/cf: send, receive, and query your inbox in code
November 23, 2026

You have a Tinbox deployed. Now you need to build on it: a receipt with a PDF, a notification fanned out to a thousand people, a reply that knows what the customer said last week. Here is the surface that gets you there.
Tinbox runs as a single Cloudflare Worker. tinbox/cf is how that Worker is assembled, and today Cloudflare is the platform Tinbox targets — so this is simply how you build with Tinbox in code, not one library option among several. If you have not deployed yet, the npx tinbox init walkthrough stands the Worker up in two commands; this article is what you do once it is running. No invented endpoints — if it is here, it ships.
The surface is three pieces, and once you see them the rest falls into place:
tinbox/cfexportscreateWorker(config)— the whole deployment (inbox API, auth, AI assistant, attachment streaming, MCP) over your bindings. This is what yourworker.tsexports.tinbox/sdkexports theTinboxclient for sending over HTTPS against your deployment's/api/send.@tinbox/engineholds the inbound-parse and inbox-query modules — the same codecreateWorkerruns internally, which you can call directly from your own routes.
What does createWorker give me?
createWorker(config) returns a Cloudflare Worker (a { fetch, email, queue, scheduled } object) wired to your D1, R2, KV, and Queues bindings. One import, the whole stack.
Your entry point is three lines:
// src/worker.ts
import { createWorker } from "tinbox/cf";
import config from "../tinbox";
export default createWorker(config);
The config (your tinbox.config.ts) declares the org, domains, and feature flags. The Worker it returns handles:
/api/trpc/*and/api/send/*: inbox operations and the Resend-style sending API/api/auth/*: better-auth (email/password plus optional GitHub OAuth)/api/chat: the streaming AI assistant/api/files/attachments/:id: authenticated attachment streaming from R2/mcp: the MCP endpoint external agents connect toemail(): inbound mail (parse, store, project for interpretation)queue()andscheduled(): campaign fan-out and journey ticks
The config type comes from tinbox/cf/types, and interpreter factories from tinbox/cf/interpreters. That is the public tinbox/cf surface. Everything else in this article is the SDK client or the engine modules the Worker uses under the hood, which you can call directly from your own routes or actions.
How do I send email beyond the basic call?
Use the Tinbox client from tinbox/sdk. Construct it once with a tbx_ API key and your deployment's /api/send base URL, then call emails.send() with html, text, cc, bcc, reply_to, custom X-* headers, and attachments.
import { Tinbox } from "tinbox/sdk";
const tinbox = new Tinbox({
apiKey: env.TINBOX_API_KEY, // a tbx_ key
baseUrl: "https://tinbox.acme.com/api/send",
});
const res = await tinbox.emails.send({
from: "Acme Billing <billing@acme.com>",
to: "ada@example.com",
cc: ["records@acme.com"],
reply_to: "support@acme.com",
subject: "Your receipt",
html: "<p>Thanks, Ada. Your receipt is attached.</p>",
text: "Thanks, Ada. Your receipt is attached.",
headers: { "X-Acme-Order": "ord_1042" },
});
console.log(res.ok, res.message_id);
// res.recipients is a per-recipient array: sent | duplicate | failed | suppressed
A few things worth knowing because they bite people:
- Always send
textalongsidehtml. A missing plain-text part is a real spam signal at the major receivers. The client lets you omit it; do not. frommust be on a domain you own and have verified. The domain owns the Message-ID. Sending from a domain Tinbox does not control is rejected (see Failure modes below).headersareX-*only. Other header names are rejected422. This stops you from forgingReceivedor auth headers by accident.- The response is per-recipient.
res.okis true only when every recipient endedsentorduplicate. A suppressed address shows up inres.suppressedand is never dispatched. That suppression list is the same one good deliverability hygiene depends on.
How do I send a receipt with an attachment?
Attachments are inline base64 on the send request: { filename, content, content_type }. Pull the bytes from R2, base64-encode them, and attach.
// Stream a stored PDF out of R2, then attach it to the receipt.
const object = await env.BLOBS.get(`receipts/ord_1042.pdf`);
if (!object) throw new Error("receipt not found in R2");
const bytes = new Uint8Array(await object.arrayBuffer());
const base64 = btoa(String.fromCharCode(...bytes));
await tinbox.emails.send({
from: "Acme Billing <billing@acme.com>",
to: "ada@example.com",
subject: "Your receipt for order 1042",
html: "<p>Your receipt is attached as a PDF.</p>",
text: "Your receipt is attached as a PDF.",
attachments: [
{ filename: "receipt-1042.pdf", content: base64, content_type: "application/pdf" },
],
});
The hard limit: the whole message (content plus headers) must stay under 5 MiB. Inline base64 inflates bytes by about a third, so a 4 MB PDF is already over budget once encoded. For anything large, do not inline it: store it in R2 and email a signed link instead. R2 storage and signed retrieval is its own topic, covered in the attachment-handling articles; the rule here is simply "small files inline, large files by link."
How do I send to a large list without timing out?
Use emails.batch(). It accepts an array of send requests and returns per-item results, and delivery runs through the queue-backed dispatcher instead of one long synchronous request.
const recipients = await loadRecipients(); // your list
const { results } = await tinbox.emails.batch(
recipients.map((r) => ({
from: "Acme <news@acme.com>",
to: r.email,
subject: "This month at Acme",
html: renderHtml(r),
text: renderText(r),
})),
);
const failed = results.filter((x) => "error" in x || x.ok === false);
console.log(`sent ${results.length - failed.length}, failed ${failed.length}`);
Two distinct paths exist and it matters which you reach for:
emails.batch()is for transactional fan-out: a few hundred to a few thousand distinct messages where you want per-item results back.- Campaigns (newsletters to an audience) are a different surface. You create the campaign in the console or via the campaign API, and the Worker's
NEWSLETTER_QUEUEconsumer paces the send across batches atNEWSLETTER_SEND_RATEper second, retrying failures and routing dead letters to the DLQ. That pacing is what keeps a 50,000-recipient blast from melting a single Worker invocation or tripping rate limits. For a true marketing list, use a campaign, not a batch loop. The queue design behind that pacing, batching, and dead-letter routing is the same set of Cloudflare Queues patterns for reliable sending the consumer is built on.
How do I receive and parse inbound mail?
createWorker already wires an email() handler that parses inbound MIME and stores it. If you want the structured fields yourself, import parseEmail from @tinbox/engine/mime: it turns raw message bytes into { from, to, subject, text, html, attachments }.
This is the same parser the inbound handler that powers the inbound handler the receive helpers power uses, so you are not running a second, divergent code path.
import { parseEmail } from "@tinbox/engine/mime";
// Inside a custom email() handler, or anywhere you hold a raw message:
const parsed = await parseEmail(rawBytes); // rawBytes: ArrayBuffer | Uint8Array
console.log(parsed.from?.address); // "ada@example.com"
console.log(parsed.subject); // "Re: my order"
console.log(parsed.text); // plain-text body, or null
console.log(parsed.html); // html body, or null
for (const att of parsed.attachments) {
console.log(att.filename, att.contentType, att.content.byteLength);
}
parseEmail handles the parts that make hand-rolled MIME parsing miserable: multipart nesting, quoted-printable and base64 transfer encodings, charset decoding, and inline-versus-attachment disposition. To persist a parsed message into the inbox the way the built-in handler does, hand it to ingestParsedEmail from @tinbox/engine/messages, which writes the message, threads it, and (if PROJECTION_QUEUE is bound) enqueues it for interpretation.
A caveat to set expectations: inbound routing is partly account-level configuration, not something the library toggles. The Worker has the email() handler, but Cloudflare still has to be told to route your domain's mail to it (Email Routing, a catch-all rule pointing at this Worker). The library handles parsing and storage; the DNS/routing wiring is a one-time dashboard step the routing tutorial walks through.
How do I query my inbox and contacts from code?
Your inbox is rows in your own D1 database, so you query it like any other table: with Drizzle against the @tinbox/engine/schema, or with searchMessages from @tinbox/engine/search for full-text. There is no remote API to call; the data is local to your Worker.
This is the payoff of the whole architecture, and it is the literal version of the idea in the stack this library drives: the inbox is a database. Reading prior context before composing a reply is a normal query.
import { drizzle } from "drizzle-orm/d1";
import { eq, desc } from "drizzle-orm";
import { messages } from "@tinbox/engine/schema";
import { searchMessages } from "@tinbox/engine/search";
const db = drizzle(env.DB);
// Recent messages from one contact, newest first:
const recent = await db
.select()
.from(messages)
.where(eq(messages.fromAddress, "ada@example.com"))
.orderBy(desc(messages.date))
.limit(10);
// Or full-text across the whole inbox (FTS5):
const hits = await searchMessages(db, { query: "refund order 1042", limit: 5 });
console.log(hits.total, hits.results.length);
searchMessages is backed by SQLite FTS5, the same index the AI agent's tools query. If you want the indexing details and the ranking knobs, the search internals cover them; here the point is that "what has this person emailed us about?" is one query against data you own, not a paginated REST crawl through someone else's service.
What does the wrangler.jsonc binding block look like?
The Worker expects DB (D1), BLOBS (R2), and KV, plus optional NEWSLETTER_QUEUE / PROJECTION_QUEUE (Queues), EMAIL (send_email), and the ASSETS binding for the inbox UI. These are exactly what npx tinbox init writes for you, so in a scaffolded project you never hand-edit this block — it is here as reference. For why these particular resources, the Cloudflare primitives every email stack is built on walks through what each one carries.
{
"name": "tinbox-acme",
"main": "src/worker.ts",
"compatibility_date": "2024-12-18",
"compatibility_flags": ["nodejs_compat"],
"d1_databases": [
{ "binding": "DB", "database_name": "tinbox-acme-db", "database_id": "..." }
],
"r2_buckets": [{ "binding": "BLOBS", "bucket_name": "tinbox-acme-mail" }],
"kv_namespaces": [{ "binding": "KV", "id": "..." }],
"send_email": [{ "name": "EMAIL" }],
"queues": {
"producers": [
{ "binding": "NEWSLETTER_QUEUE", "queue": "tinbox-acme-newsletter" },
{ "binding": "PROJECTION_QUEUE", "queue": "tinbox-acme-projection" }
],
"consumers": [
{
"queue": "tinbox-acme-newsletter",
"max_batch_size": 10,
"dead_letter_queue": "tinbox-acme-newsletter-dlq"
},
{ "queue": "tinbox-acme-projection", "max_batch_size": 10 }
]
}
}
The binding names (DB, BLOBS, KV, NEWSLETTER_QUEUE, PROJECTION_QUEUE, EMAIL) are what the library looks up at runtime; the Cloudflare resource names (tinbox-acme-*) are scoped per org so many tenants can share one Cloudflare account via separate deploys. Note that one deploy serves one brand/domain: multi-domain-per-instance is designed but not yet built, so a second client means a second deploy.
What are the common failure modes?
The errors you will actually hit are missing bindings, an unverified from domain, an oversized attachment, and a queue that is not bound. Each has a clear message and a one-line fix.
Missing queue binding. If you try a campaign or batch fan-out without NEWSLETTER_QUEUE wired, the dispatcher cannot enqueue:
TypeError: Cannot read properties of undefined (reading 'send')
at dispatcher (NEWSLETTER_QUEUE is not bound)
Fix: add the NEWSLETTER_QUEUE producer and consumer to wrangler.jsonc (the block above), then wrangler deploy. Single transactional sends via emails.send() do not need the queue; only batch and campaign paths do.
Unverified from domain. Sending from a domain Tinbox does not control:
TinboxError 422: from address domain "randodomain.com" is not a verified sending domain
Fix: send only from SENDING_DOMAIN (or an alias you have set up with SPF/DKIM). The auth-record setup is covered in SPF, DKIM, and DMARC setup.
Oversized attachment. Inline content pushes the message past the cap:
TinboxError 422: message exceeds 5 MiB limit (content + headers)
Fix: store the file in R2 and send a signed link instead of inlining the bytes. The base64 inflation is what tips a "4 MB" file over a 5 MiB budget.
Missing DB binding. The most basic one, usually a typo in wrangler.jsonc:
Error: env.DB is undefined (D1 binding "DB" not found)
Fix: confirm the d1_databases binding is named exactly DB. The library looks up bindings by name; rename the binding, not the variable.
Where to go deeper
This is the layer you build features on; the surrounding articles cover the pieces it leans on. For why outbound is HTTPS and not SMTP at the edge, read why you can't send over SMTP from a Worker. For inbound, the inbound handler the receive helpers power shows the routing setup the email() handler completes. The query side reads the same data the AI agent's tools query, so a feature you build and a question the agent answers read from one inbox.
You now have the full surface: createWorker for the deployment, the Tinbox client for sends and batches, parseEmail and ingestParsedEmail for inbound, and Drizzle plus searchMessages for reading your own inbox. That is enough to build a receipt-with-attachment flow, a notification fan-out, and a contact-aware reply: real features, not a hello-world send.
Haven't deployed yet? npx tinbox init <domain> scaffolds the worker.ts, tinbox.config.ts, and wrangler.jsonc shown here so the bindings match on the first deploy — see the full walkthrough. The API reference for tinbox/cf, tinbox/sdk, and the engine modules lives in the docs.
Frequently asked questions
How do I send email with attachments from a Worker?
Use the tinbox/sdk Tinbox client: call emails.send({ from, to, subject, html, text, attachments }). Each attachment is { filename, content, content_type } where content is base64. The whole message (content plus headers) must stay under 5 MiB, so large files belong in R2 with a signed link instead of inline.
Can I query my inbox from code?
Yes. The inbox lives in your own D1 database, so you read it with Drizzle against the @tinbox/engine schema, or use searchMessages from @tinbox/engine/search for FTS5 full-text queries. These are the same helpers the Worker and the AI agent's tools use, so there is no separate API to call.
What bindings does tinbox/cf need?
DB (D1), BLOBS (R2), and KV are required. NEWSLETTER_QUEUE and PROJECTION_QUEUE (Queues) enable campaign fan-out and inbound projection. EMAIL (send_email) enables outbound. These match the wrangler.jsonc that npx tinbox init writes, so you do not configure them twice.
How do I send from my own code once Tinbox is deployed?
Your deployment exposes a Resend-style send API at /api/send. From your app or another Worker you call it with the tinbox/sdk Tinbox client (or a plain fetch) using a tbx_ key. Inbound parsing and inbox queries are done with the @tinbox/engine modules the Worker already runs, against your own D1 — there is no separate service to call.
How do I receive and parse inbound mail?
createWorker already wires an email() handler that parses inbound MIME with parseEmail and stores it with ingestParsedEmail. If you want to handle a raw message yourself, import parseEmail from @tinbox/engine/mime to turn the raw bytes into structured { from, to, subject, text, html, attachments } fields.