# Update flags and labels for multiple messages or whole conversations

Applies flag, label, and keyword updates across multiple messages in a single atomic operation. Name the targets by `ids`, by `threadIds`, or both: `threadIds` is expanded to the conversation's members server-side, in the same transaction as the write, so a reply that arrives while the request is in flight is either wholly in the gesture or wholly outside it. That is the difference from expanding it client-side, which also truncates at whatever page of members the client happened to hold. Expansion is the set GET /threads/{threadId} returns: live members in your grant, Trash and Junk excluded. `ids` may name a trashed, junked or otherwise excluded message directly — the operand chooses targets, it does not restrict them.

## `PATCH /api/v1/mailboxes/{mailboxId}/messages`

### Path parameters

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

### Request body (optional)

`application/json`

- `flagLabel` (string, min 1 chars) — The label (IMAP mailbox) the client had selected. When present, `deleted` in `flagsSet`/`flagsClear` marks the message's membership in THAT label only, leaves the message-wide bit untouched, and every other flag in the same patch keeps its message-wide meaning. Label-scoped listings (`/labels/{label}/uids`, `/labels/{label}/messages`, the label-filtered search) report this per-membership bit, `deletedCount` counts it, and `POST /labels/{label}/expunge` detaches exactly the memberships carrying it. A label the message is not filed in answers not_in_label with nothing written. Requires `deleted` in one of the two flag lists (validation_failed otherwise). Without `flagLabel`, `deleted` means every folder: the message-wide bit (JMAP's visibility rule; JMAP has no `\Deleted`) and every membership move together. A scoped clear that unmarks the last marked membership clears the message-wide bit as well.
- `flagsClear` ("seen" | "answered" | "flagged" | "draft" | "deleted"[]) — Flags to remove
- `flagsSet` ("seen" | "answered" | "flagged" | "draft" | "deleted"[]) — Flags to set
- `ids` (string[], min 1 items, max 200 items) — Array of message IDs to update
- `ifInLabel` (object) — Apply each explicit ID only while it has the given UID in this label and UIDVALIDITY epoch. Checked atomically with the write; the identity condition alone permits intervening flag changes. Missing UID entries, absent or replaced memberships, and inaccessible labels answer not_in_label per entry, with nothing written. Cannot be combined with threadIds.
  - `label` (string, required, min 1 chars)
  - `uids` (object, required)
  - `uidValidity` (integer, required, ≥ 1, ≤ 4294967295)
  - `unchangedSince` (object) — Optional per-ID modseq ceilings in this label (at most 200 entries). A newer membership answers modified with its currentModseq; a missing entry answers not_in_label. Zero refuses every existing membership. Checked in addition to the top-level unchangedSince, if supplied.
- `keywordsClear` (string[]) — Custom keywords to remove
- `keywordsExact` (string[]) — Exact replacement list of custom keywords
- `keywordsSet` (string[]) — Custom keywords to add
- `label` (string, min 1 chars) — Label context for unchangedSince check
- `labelsAdd` (string[]) — Labels to add
- `labelsExact` (string[]) — Exact replacement list of labels
- `labelsRemove` (string[]) — Labels to remove
- `orphans` ("expunge" | "archive") — What to do if this write would leave the message with no label. 'expunge' (the default) sends the message to Recently deleted. 'archive' keeps the message live by attaching the Archive system label (attaching Archive needs no right beyond the grant's 't' for a scoped viewer). If the write removes Archive itself and would leave no labels, Archive is kept without error. A SCOPED viewer whose write lands the message in Archive has moved it out of their own scope: the answer is still `updated`, and the hydrated message carries an EMPTY `labels` list rather than naming a label the grant never included. `labelsAdded` omits Archive for the same reason.
- `threadExcludeRoles` ("inbox" | "sent" | "drafts" | "trash" | "archive" | "junk"[]) — Roles to exclude from thread expansion (e.g. ['sent', 'drafts']). Members carrying any label with one of these roles are omitted from the expanded conversation. Trash and Junk members are already left out by the default expansion, so naming them here changes nothing unless `threadLabel` is that folder, where it empties the set. Explicit `ids` are unaffected. If every member is excluded, the conversation contributes nothing, which is not an error.
- `threadIds` (string[], min 1 items, max 50 items) — Conversation IDs whose members to update, expanded server-side. A stale ID from before a thread merge resolves transparently, as on GET /threads/{threadId}. Refused with thread_too_large past 1000 expanded messages, rather than acting on some of them.
- `threadLabel` (string, min 1 chars) — The folder each conversation in `threadIds` was being viewed in — the same value passed to GET /threads/{threadId}?label=, so the patch reaches exactly the members that view rendered. Omitted, the expansion is the default view: live members in your grant with Trash and Junk excluded. Pass the Trash folder to patch a conversation's trashed members instead, or the Junk folder for its junked ones; the default deliberately leaves both alone. Optional here and REQUIRED on DELETE /messages, where guessing wrong destroys a member the user was not looking at rather than re-filing one they can see.
- `threadLabelOnly` (boolean) — Narrow each conversation in `threadIds` to the members FILED UNDER `threadLabel`, which is then REQUIRED (thread_context_required without it). `threadLabel` alone is a view, not a filter: a conversation viewed in the Inbox includes the Sent copy of your replies and any member filed elsewhere, so a label patch over it re-files those too. Pass this for FILING gestures (archive, move, junk, delete-to-Trash) so they act on what the folder listing showed; leave it off for flags and keywords, which mean the whole conversation. `ids` are unaffected.
- `unchangedSince` (integer, ≥ 0) — Conditional update precondition: update only if modseq <= unchangedSince

### Responses

**200** — Batch update results per message. An entry answers not_in_label when flagLabel names a label that message is not filed in, or ifInLabel does not match its current accessible membership (nothing written for it)

`application/json` → BatchUpdateResult

- `results` (BatchUpdateEntry[], required) — List of update outcomes for each requested message
  - `id` (string, required) — Message ULID
  - `status` ("updated" | "expunged" | "not_found" | "not_in_label" | "too_many_keywords" | "modified", required) — Outcome status for this message. `not_in_label`: the patch named a `flagLabel` this message is not filed in, so nothing was written for it
  - `currentModseq` (integer <int64>) — Current message MODSEQ value on CAS conflict
  - `expungedAt` (integer <int64>) — Expunge timestamp in epoch seconds (when status=expunged)
  - `labelsAdded` (string[]) — Labels attached by this write
  - `labelsRemoved` (string[]) — Labels detached by this write
  - `message` (MessageMeta & object)
    - `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)
  - `modified` (boolean) — True if CAS check failed due to concurrent modification
  - `modseq` (integer <int64>) — Updated or current MODSEQ value
  - `purgeAfter` (integer <int64>) — Purge deadline timestamp in epoch seconds (when status=expunged)

**400** — validation_failed (including flagLabel without `deleted` in either flag list, malformed ifInLabel, or ifInLabel with threadIds), invalid label/keyword, target_required (neither ids nor threadIds given), thread_context_required (threadLabelOnly without threadLabel), or thread_too_large

`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 PATCH 'https://api.open.email/api/v1/mailboxes/{mailboxId}/messages' \
  -H 'Authorization: Bearer oek_…' \
  -H 'Content-Type: application/json' \
  -d '{}'
```

## TypeScript SDK

[`openemail.messages.updateMany`](/docs/sdks/typescript/messages/update-many)

```ts
const batchUpdateResult = await openemail.messages.updateMany(mailboxId, {})
```
