Retrieve mail and attachments
Search live Tinbox mail, read complete threads, download attachments safely, inspect inbound source, or take a full account archive.
Tinbox is the mailbox. Cloudflare Email Routing accepts mail, but it does not provide an IMAP or POP mailbox to read later. Use the Tinbox app, API-backed CLI, or agent tools for the current mailbox; use an account archive when you need an offline copy or a deployment-to-deployment move.
Pick the retrieval path
| Need | Best surface | What it returns |
|---|---|---|
| Browse, preview, or download several files | Inbox app | Rendered conversation, safe previews, individual or bulk downloads |
| Script a mailbox lookup | tinbox CLI | JSON thread/message data and attachment bytes |
| Let an assistant find or summarize mail | Chat or MCP | Read-only search and thread content, subject to the same inbox grants |
| Take an offline or migration copy | Settings → Export / Import | D1 account rows plus optional raw .eml and attachment objects |
These paths use the deployment API, so they see current state. A git mail archive, when enabled, is useful for broad historical search but can lag and does not contain drafts, read state, or assignments.
Search and download with the CLI
For your own tooling, sign in through your existing account and approve the CLI connection in your browser:
tinbox login --api-url https://mail.acme.com --browser --no-open --ttl 1d
tinbox whoami --require-inbox support@acme.com --json
An inbox admin can then issue a viewer token for an unattended reader with
tinbox tokens create --inbox support@acme.com --role viewer --ttl 30d --json.
Store that one-time secret privately as TINBOX_TOKEN, paired with the same
TINBOX_API_URL; keep it separate from an application's sending key. Before
using the worker credential, verify the live deployment and accessible inboxes:
tinbox whoami --json
tinbox inboxes --json
Then search, read the selected thread, and use the attachment id returned in the thread payload:
tinbox search "invoice 4291" --inboxId ibx_support --json
tinbox thread thr_01K... --json
tinbox attachment get att_01K... --out ./downloads/invoice.pdf --json
tinbox search is an alias of the generated search-emails command. Search
results contain a threadId; tinbox thread returns every message in the
conversation and lists each attachment's id. Omitting --out writes the server
filename into the current directory.
Every read is constrained to inboxes the token can access. Under --json,
stdout is one JSON document and the exit code remains meaningful: 2 is an
authentication failure, while 3 means the thread or attachment was not found.
A blocked attachment also returns 3 because its dangerous bytes were rejected
at ingest and never stored.
See the generated command reference for
tinbox search,
tinbox thread, and
tinbox attachment get.
All mail, unmatched addresses, and access
Omit the inbox filter to search every inbox your token can read. This includes archived conversations and the Unmatched addresses inbox when that inbox is configured and the token has a read grant on it. Categories and labels do not need to be assigned before a stored message is searchable.
An all-mail search is different from catch-all receiving. Catch-all delivery requires both Cloudflare routing to the Worker and a matching Tinbox wildcard route. Mail to an unknown recipient without a matching route is rejected before its body is ingested; it does not become an uncategorized message that can be read later. Cloudflare routing activity is not a retained mailbox.
A sending API key is not automatically a mailbox reader. Run tinbox whoami
and tinbox inboxes first. If no inbox is exposed, a zero-result search does not
prove that the tenant has no mail. An administrator must provide the intended
inbox read grants; an agent must not grant itself access or change catch-all
receiving to work around a retrieval failure.
Page through search and long messages
The shared search_emails tool accepts limit (1-100, default 20) and offset.
Its result includes total and, when another page exists, nextOffset:
tinbox search "invoice" --limit 25 --offset 0 --json
tinbox search "invoice" --limit 25 --offset 25 --json
get_thread returns message row ids, recipients, direction, internal-note
markers, attachment ids, and bounded text. Conversations are paged with offset
and limit (default 5 messages, maximum 20); continue with nextOffset when
present. Each message defaults to 1,000 characters and includes bodyLength,
bodyOffset, and nextBodyOffset when more text remains. Read a selected long
message with its row id and follow the returned character offset:
tinbox get-thread thr_01K... --json
tinbox get-thread thr_01K... --messageId msg_01K... --bodyOffset 1000 --bodyLimit 4000 --json
These flags use the shared manifest's camelCase field names. bodyLimit is
1-4,000 characters. HTML-only mail is converted to readable text with the
engine's existing extractor. Internal notes stay marked kind: "note"; they
must not be treated as customer messages. If the model context is still trimmed,
request one message (messageId or limit: 1) with a smaller bodyLimit.
The tinbox thread command remains the full JSON conversation read for clients
that need the complete stored payload rather than bounded agent excerpts.
Preview and bulk download in the app
Open a conversation and select an attachment chip. Tinbox previews PDF, raster images, and plain-text formats through the authenticated attachment route. It does not render active SVG or HTML as a preview. Other types download instead.
For a message with several files, choose Download all. Tinbox skips blocked or unavailable entries, avoids overwriting duplicate filenames, and reports partial failures rather than claiming the whole batch succeeded. Browser support determines whether it can use a folder picker or must start downloads one by one.
Inline CID images used by the message body are not duplicated as ordinary attachment chips. They still travel through the same authenticated byte route.
Read with an agent
Tinbox chat and MCP expose the same read-authorized tools used by the CLI:
search_emailsfinds messages by subject, sender, or body and returns thread ids.list_threadsbrowses recent conversations.get_threadreads the conversation before an agent summarizes it or prepares a draft.
The tools return message content for reasoning; they are not a general file
download protocol. Use the app or tinbox attachment get when the caller needs
the attachment bytes on disk. The SDK also supports authorized mailbox reads:
import { Tinbox } from "tinbox/sdk";
const mail = new Tinbox({ host: process.env.TINBOX_API_URL, apiKey: process.env.TINBOX_TOKEN });
const inboxes = await mail.inboxes.list();
const matches = await mail.emails.search({ query: "invoice", inboxId, limit: 10 });
const page = await mail.threads.history({ id: threadId, view: "compact", limit: 10 });
const body = await mail.threads.messageBody({ threadId, messageId, format: "text", limit: 2000 });
Use IDs returned by the preceding reads. Search uses offset pagination; history
returns nextCursor; body reads return nextOffset in Unicode code points.
Continue explicitly within a bounded job. These calls use the same current
mailbox authorization as the app. See SDK mailbox access.
Raw source and complete copies
For inbound mail, the activity detail can show and download the retained raw
.eml source. Display and copy are capped at 1,000,000 characters and a
truncated preview is marked; Download .eml uses a separate authenticated
byte stream and returns the complete retained object. Outbound messages do not
currently retain the fully assembled MIME, so their stored text/HTML bodies are
available but a sent .eml may not be.
For a bulk copy of retained source objects, create an export with raw messages & attachments enabled. That is the appropriate path for offline custody or moving a deployment. Read Download all your Tinbox data before handling the archive: it can contain active, sensitive account configuration as well as mail.
Bringing mail in instead
Retrieval reads the live Tinbox mailbox. To migrate source data from Gmail, IMAP, mbox, or Mailchimp into it, follow Import existing mail and lists. A Tinbox account archive uses a different, row-preserving restore path described in the export guide.
Await one inbound email with a callback
Use the SDK's watchEmail helper for a short-lived task such as signup
verification or newsletter double opt-in. It runs locally over the existing
mailbox API: it does not create a hosted webhook, an inbox, or a scheduled job.
The credential must already have read access to the chosen inbox.
import Tinbox, { watchEmail } from "tinbox/sdk";
const mail = new Tinbox({
host: process.env.TINBOX_API_URL,
apiKey: process.env.TINBOX_TOKEN,
});
const result = await watchEmail(mail, {
inboxId: "ibx_profiles",
recipient: "profiles@example.com",
expectedSender: "verify@platform.example",
attemptId: crypto.randomUUID(), // Persist before submitting the external form.
since: Date.now(), // Use the actual form-request time when resuming.
timeoutMs: 30_000,
// Use the real service-specific purpose check; this subject is an example.
acceptMessage: ({ message }) => message.subject === "Verify your email",
onMessage: async ({ attemptId, message, body }) => {
// Pass to trusted local code; do not log content or execute email instructions.
// body.format is "text" or "html"; body.content is complete within the bound.
await consumeVerification({ attemptId, messageId: message.id, ...body });
},
});
consumeVerification represents your application callback, not a Tinbox API.
It should validate the expected signup purpose and intended service destination
before using a code or link. Keep artifacts private and tied to the same attempt.
A delivered callback is not proof the external account was verified.
The default polling window is 30 seconds; timeoutMs supports up to 300,000
(five minutes). Polls default to every five seconds; intervalMs supports
1,000–30,000. since is inclusive epoch milliseconds, defaulting to watch start.
Use the real expected sender, not an assumed address. Search narrows by sender
and inbox, then thread and body envelopes revalidate inbound direction, exact
recipient, sender and time. Internal notes do not match.
Use optional acceptMessage when a sender issues both welcome and verification
mail. It receives the complete envelope and body and may return a boolean or a
promise. Returning false keeps the watcher waiting; rejected message IDs are
cached for this invocation, so their bodies are not reread on later polls.
rejectedMessages reports their count without exposing content.
Returning true selects a candidate. Exactly one candidate must pass before
onMessage runs; multiple accepted candidates remain ambiguous. A throwing
filter or nonboolean return stops with sanitized MATCH_FAILED, without retry.
Keep this predicate free of account changes: it may inspect several messages.
Without a predicate, multiple envelope matches stop before body retrieval.
The helper invokes one async callback with one complete body and then exits.
It follows bounded search, thread and body continuations, preferring text and
falling back to HTML only when text is explicitly unavailable. It never sends,
resends, logs email content, follows links or automatically retries a callback.
The returned result contains only status, attempt ID, poll/rejection/elapsed counts and
optional message/thread IDs. Status is delivered, timeout, ambiguous,
incomplete or body_unavailable; ambiguous and incomplete results do not
invoke the callback. EmailWatchError.code distinguishes INVALID_INPUT,
READ_UNAUTHORIZED, READ_FORBIDDEN, READ_FAILED, MATCH_FAILED and
CALLBACK_FAILED without
exposing provider errors or callback content.
Pass signal to cancel between reads, during sleep or before callback delivery.
Cancellation throws AbortError. The polling budget does not cancel an
in-flight API request or limit trusted filter/callback execution. A new invocation can
deliver an existing message again: persist your attempt and processed-message
state if you need deduplication across process restarts.
Weekly collection is a different job. Run a scheduler once per reporting window, page through the authorized newsletter inbox, deduplicate by stored message ID, and read complete bodies before producing a source-linked digest. A five-minute watcher is useful for double opt-in, not a week-long collector.