# Structured filter and query messages

Executes a structured query over mailbox messages with complex filters (combinators, header conditions, date ranges, flag states) and custom sort orders.

## `POST /api/v1/mailboxes/{mailboxId}/search/query`

### Path parameters

- `mailboxId` (string, required) — Mailbox ULID identifier

### Request body (optional)

`application/json`

- `calculateTotal` (boolean) — Also return the total number of matches (an extra count).
- `collapseThreads` (boolean) — Return one representative message per conversation.
- `excludeRoles` ("inbox" | "sent" | "drafts" | "trash" | "archive" | "junk"[]) — System label roles whose mail this query must not return — e.g. `["trash", "junk"]` for an All-Mail view. A message carrying ANY label with one of these roles is excluded, whatever else it carries. Says in one argument what a filter would need a label lookup and one bound value per label to say; a role no label answers to is simply not excluded.
- `fields` ("ids") — `ids`: answer the matching message IDS only, in query order, under `ids` — no metadata rows, page cap 2000. For a client that needs an id set (an IMAP SEARCH with header or BODY criteria) and would otherwise download bodies to decide. Not combinable with `snippet`.
- `filter` (EmailSearchFilter) — An RFC 8621 §4.4 FilterCondition, or a boolean tree of them ({operator: AND|OR|NOT, conditions: [...]}). Bounded, and refused (never truncated) past the bound: the tree at most 32 levels deep and 512 nodes, and at most 64 bound values in total (an inMailboxOtherThan element costs one each).
  - _option 1: EmailSearchFilterOperator_
    - `conditions` (EmailSearchFilter[], required) — Nested filters: each is itself an EmailSearchFilter (condition or operator)
      - _recursive: EmailSearchFilter_
    - `operator` ("AND" | "OR" | "NOT", required) — How the nested conditions combine (RFC 8620 §5.5 FilterOperator)
  - _option 2: EmailSearchCondition_
    - `after` (string) — Received at or after this RFC 8620 UTCDate (e.g. 2026-08-01T00:00:00Z)
    - `allInThreadHaveKeyword` (string) — Every live message in the conversation carries this keyword
    - `bcc` (string) — Substring of the Bcc addresses (max 50 bytes)
    - `before` (string) — Received strictly before this RFC 8620 UTCDate (e.g. 2026-08-01T00:00:00Z), the one place this API departs from epoch seconds
    - `body` (string) — Full-text match over the body parts
    - `cc` (string) — Substring of the Cc addresses (max 50 bytes)
    - `from` (string) — Substring of the From addresses (max 50 bytes)
    - `hasAttachment` (boolean) — Whether the message has file attachments
    - `hasKeyword` (string) — The message carries this keyword or flag (e.g. $seen, $flagged, $forwarded)
    - `header` (string[], min 1 items, max 2 items) — [name] = the header is present; [name, value] = the header contains value. Indexed names only: subject, message-id, in-reply-to, from, to, cc, list-id
    - `inMailbox` (string) — Only messages in this Mailbox, as L<labelId>: the `id` from GET /mailboxes/{mailboxId}/labels prefixed with L (INBOX is usually L1)
    - `inMailboxOtherThan` (string[]) — Only messages in at least one Mailbox NOT listed (same L<labelId> ids)
    - `maxSize` (integer) — Size in bytes is strictly below this
    - `minSize` (integer) — Size in bytes is at least this
    - `noneInThreadHaveKeyword` (string) — No live message in the conversation carries this keyword
    - `notKeyword` (string) — The message does NOT carry this keyword
    - `someInThreadHaveKeyword` (string) — At least one live message in the conversation carries this keyword
    - `subject` (string) — Full-text match over the Subject header
    - `text` (string) — Full-text match over the whole message (subject and bodies)
    - `to` (string) — Substring of the To addresses (max 50 bytes)
- `limit` (integer, ≥ 1, ≤ 2000) — Page size; capped at 200, defaults to 25 — or up to 2000 with `fields: "ids"`.
- `position` (integer) — Zero-based offset into the result list. A negative value counts back from the end (RFC 8620 §5.5).
- `snippet` (boolean) — Also return highlighted <mark> excerpts (subject + body preview) for the matched text terms of this page's results. Each excerpt costs a body read, so at most the first 50 results carry one.
- `sort` (EmailSearchComparator[], max 4 items) — Up to 4 comparators; an id tiebreak is always appended so the order is total.

### Responses

**200** — Search results page with optional total count and snippets

`application/json` → EmailSearchResult

- `position` (integer <int64>, required) — Zero-based index of the first result within total matches
- `results` (MessageMeta[], required) — List of matching messages for the current page
  - `auth` (MessageAuth, required) — Stored SMTP authentication and original inbound junk verdicts. Missing verdicts are null; the object is null when none were recorded (including APPEND and local Sent copies). Junk does not follow later label changes.
    - `arc` (string | null, required) — ARC verdict, or null
    - `dkim` (string | null, required) — DKIM verdict, or null
    - `dmarc` (string | null, required) — DMARC verdict, or null
    - `junk` (boolean | null, required) — The inbound spam verdict (X-OpenEmail-Junk), or null when none was stamped
    - `spf` (string | null, required) — SPF verdict (pass/fail/softfail/none/...), or null
  - `bcc` (array | null, required) — Parsed Bcc header addresses for composed drafts, or null
  - `blobGen` (string, required) — Storage generation identifier
  - `blobHash` (string, required) — SHA-256 hash of raw MIME content in storage
  - `cc` (array | null, required) — Parsed Cc header addresses, or null if unparseable
  - `deliveryMeta` (object | null, required) — Inbound delivery audit metadata
  - `deliveryState` ("queued" | "relayed" | "delivered" | "failed" | "mixed" | null, required) — What became of this message after it was SENT, for a message this mailbox sent: 'queued' (handed to the relay), 'relayed' (the receiving mail system accepted it — never 'read'), 'delivered' (committed to a local mailbox), 'failed', or 'mixed' (some recipients failed, others did not). Null for received mail, and for sent mail whose delivery record has aged out — render null as no indicator, never as a state. Per-recipient detail and the SMTP reply behind a failure are at /messages/{messageId}/delivery.
    - _option 1: "queued" | "relayed" | "delivered" | "failed" | "mixed"_
    - _option 2: null_
    - _option 3: null_
  - `envelopeFrom` (string, required) — SMTP envelope sender address
  - `envelopeTo` (string, required) — SMTP envelope recipient address
  - `flags` (string[], required) — System flags (seen, answered, flagged, draft, deleted)
  - `from` (array | null, required) — Parsed From header addresses, or null if unparseable
  - `hasAttachment` (boolean | null, required) — True if message has file attachments, null if not yet determined
  - `id` (string, required) — Unique message identifier (ULID)
  - `inReplyTo` (string | null, required) — In-Reply-To header Message-ID, or null
  - `keywords` (string[], required) — Custom JMAP keywords (e.g. $forwarded)
  - `labels` (MessageLabel[], required) — Labels attached to this message with per-label UIDs
    - `deleted` (boolean, required) — This membership's IMAP \Deleted mark (set with `flagLabel` on PATCH, acted on by POST /labels/{label}/expunge). Always present; false when unmarked. Per label, so the same message can be marked in one folder and clean in another
    - `modseq` (integer <int64>, required) — RFC 7162 MODSEQ change sequence number
    - `name` (string, required) — Label name
    - `uid` (integer <int64>, required) — Message UID inside this label
    - `uidValidity` (integer <int64>, required) — UID validity epoch of the label
  - `messageIdHeader` (string | null, required) — Message-ID header value, or null
  - `receivedAt` (integer <int64>, required) — Timestamp when message was received by server in epoch seconds
  - `referencesIds` (string[], required) — List of Message-IDs from References header
  - `sentAt` (integer | null, required) — Sent timestamp from Date header in epoch seconds, or null
  - `size` (integer <int64>, required) — Total message size in bytes
  - `snippet` (string | null, required) — Short plain-text preview of message body
  - `subject` (string | null, required) — Message subject line, or null
  - `threadId` (string | null, required) — Conversation thread identifier (ULID), or null
  - `to` (array | null, required) — Parsed To header addresses, or null if unparseable
  - `modseq` (integer <int64>) — Per-label MODSEQ (present in label UID listings)
  - `restoresTo` (array | null) — Where a recovery would file this message, as label names. Present only when the message is recoverable: one carrying the Trash label (POST /messages/untrash), one carrying the Junk label with a recorded origin (POST /messages/unjunk), or one on the expunged tier (POST /messages/restore). A message in both Trash and Junk's records answers for Trash, the verb a client offers it first. Null otherwise, meaning the message is filed rather than recoverable. This is the effective destination including the Inbox fallback, not a raw snapshot, so a client can name it on a Put back or Not spam control without reimplementing the rule.
  - `uid` (integer <int64>) — Per-label UID (present in label UID listings)
- `ids` (string[]) — With `fields: "ids"`: the matching message IDs in query order (`results` is then empty)
- `limit` (integer <int64>) — Effective page size limit applied by the server
- `scanWindow` (integer <int64>) — The cap that clipped: the collapsed results were drawn from the newest this-many matching messages. Present only beside `truncated`, so a client can say "more than N matches" with the N the server applied.
- `snippets` (EmailSearchSnippet[]) — List of search term highlighted snippets for results
  - `id` (string, required) — Message ULID this snippet belongs to
  - `preview` (string | null, required) — Highlighted HTML snippet for the message body, or null if not matched
  - `subject` (string | null, required) — Highlighted HTML snippet for the subject line, or null if not matched
- `total` (integer <int64>) — Total number of matching messages (when calculateTotal was true)
- `truncated` (boolean) — Present (true) only on a collapseThreads query whose scan hit the server's row cap: the collapsed result set covers the newest matches, not all of them, and positional paging ends when that set does even though `total` (when requested) counts the whole match set. Present on EVERY page of such a query, not only the last, so a client can say so from page one.

**400** — validation_failed, unsupported_filter, unsupported_sort, or invalid_filter

`application/json` → ErrorOrValidation

**401** — unauthorized: the bearer credential is missing, malformed, expired, or revoked. Carries a `WWW-Authenticate: Bearer` challenge

`application/json` → ErrorBody

**404** — Mailbox not found or not accessible to this principal

`application/json` → ErrorBody

**413** — too_large: JSON request body exceeds 1 MiB or 500,000 values (object keys included), checked before parsing

`application/json` → ErrorBody

**503** — temporary_failure: the platform's storage could not answer just now; retry after the Retry-After window. Any operation can answer this. A write that got it may have been applied, so retry it with the same idempotency key where it takes one, or read the state back first (see Transient failures in the API description)

`application/json` → ErrorBody

### Example request

```bash
curl -X POST 'https://api.open.email/api/v1/mailboxes/{mailboxId}/search/query' \
  -H 'Authorization: Bearer oek_…' \
  -H 'Content-Type: application/json' \
  -d '{}'
```

## TypeScript SDK

[`openemail.search.query`](/docs/sdks/typescript/search/query)

```ts
const emailSearchResult = await openemail.search.query(mailboxId, {})
```
