---
title: "nextmail.threads"
description: "Every method in this namespace: its signature, its parameters, what it returns and an example."
url: "https://nextmail.sh/docs/python/reference/threads"
area: "Python"
category: "Reference"
---

# nextmail.threads

Every method in this namespace: its signature, its parameters, what it returns and an example.

## Methods

Read, search, label, trash, snooze and mute conversations in the mailbox, read the inbox one tab at a time, choose the tab the mail of a sender always goes to, show the team you are replying, and see how the mail sent in a conversation was read, whether it arrived and which download links it carried.

### `threads.list()`

List one page of threads in a folder

```python
def list(
    *,
    limit: int | None = None,
    cursor: str | None = None,
    folder: str | None = None,
    query: str | None = None,
    label_ids: str | Sequence[str] | None = None,
    sort: ThreadSort | None = None,
    date_from: datetime | str | None = None,
    date_to: datetime | str | None = None,
    from_contacts: bool | None = None,
    semantic: bool | None = None,
    category: InboxCategory | None = None,
    address: str | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> Page[ThreadSummaryResource]
```

Returns one page of threads from the mailbox index, ordered by each thread's latest message with the newest first unless `sort` says otherwise. A row is only `object` and `id`, so call `get` for the messages, labels and unread state.

`sort`, `date_from=`, `date_to=` and `from_contacts=` are the thread list's own controls: the four orders, a date range read against the newest message on each thread, and a filter to mail from saved contacts. Every order pages to the end, and a cursor carries on in the order it was handed out in, so send the same filters with it.

`folder` defaults to `inbox` and is matched against label ids after being upper cased, so `sent`, `archive`, `spam`, `trash`, `draft`, `snoozed`, `starred` and `unread` all work, `bin` is read as `trash`, and a user label id works as a folder too. A name that matches nothing returns an empty page rather than an error. `label_ids=` narrows the folder further: a thread must carry the folder label and every id you pass. `category=` keeps one inbox tab, `primary`, `promotions`, `updates`, `social` or `forums`, where `primary` is every thread in no other tab.

`query` takes the mailbox search syntax. Plain words must all appear, and each matches loosely: case, accents and separators are ignored and part of a longer word counts, so `min` finds "Benjamin". A quoted phrase is matched as written apart from case and accents, so `"ben jamin"` does not find "Ben-Jamin" while `"quarterly invoice"` finds "Quarterly invoice". When nothing matches exactly, close spellings are returned instead, so `benjimin` finds "Benjamin": a plain word, or the value of `from:`, `to:`, `cc:`, `subject:`, `body:`, `filename:` or `label:`, may differ from the start of a word by one typo when it has four to seven letters and by two when it has eight or more, while a quoted phrase, a word containing a digit, a shorter word and an excluded word still match exactly, and the pages that follow keep matching the same way. Filler words such as `the`, `about` or `emails` are dropped from a list of plain words when something else is left to search for, so `emails from john` searches for `john` alone. Operators such as `from:`, `to:`, `subject:`, `label:`, `is:unread`, `has:pdf`, `after:2026/01/31` and `newer_than:7d` narrow it, and `OR`, parentheses and a leading `-` combine them. `is:muted` finds muted threads, `is:waiting` the threads with a reminder nobody has answered yet, and `category:promotions` one inbox tab in any folder. Recipients are stored as one list without roles and never hold a Bcc, so `cc:` reads the same field as `to:` and `bcc:` matches nothing of its own. `from:me` is mail you sent, and `to:me` is mail carrying one of your own addresses, aliases included, among its recipients or as the address it was delivered to.

With `semantic=True` the plain words of `query` match by meaning rather than spelling. Describe the mail in a few words, `flight to Berlin` or `invoices I still owe`, in any language, and the threads closest in meaning come back best match first, together with every thread the words match as text, which ranks above one that only means the same. A thread is kept only when it is clearly closer to the words than the rest of the mailbox, so a description nothing fits returns only the text matches. Operators and filters narrow it as usual, `sort` does not apply, and a query with no plain words is a text search whatever `semantic=` says. Meaning is read from the whole conversation, newest messages first, so an earlier message counts too, and a workspace that turned search by meaning off in its settings gets a text search instead.

Words and the `from:`, `to:`, `cc:`, `subject:` and `body:` operators read only the newest message on each thread: its sender, its recipients, its subject and the first 4,000 characters of its body with markup stripped. `filename:` and `has:` read every attachment on the whole conversation, and `label:`, `in:` and `is:` read the whole conversation. A plain word also matches the name of any attachment on the conversation, whichever message carried it. A sealed message has no body text to match. The search stays inside `folder` unless the query names a folder itself, with `in:` or a folder `is:` such as `is:sent`, and `in:anywhere` searches every folder, on its own as well as beside other terms. A drafts listing is the exception and stays in drafts whatever the query names.

Dates read the newest activity on the thread, in UTC. `after:` includes the day it names and `before:` excludes it, and a date can be written `YYYY/MM/DD`, `YYYY-MM-DD`, `YYYYMMDD`, as a bare year, or as epoch seconds or milliseconds. A short date reads day first (`16/09/2026`), unless the second number cannot be a month (`09/16/2026`), and a number above 12 settles it either way. The API pages with an opaque `pageToken`, which the SDK hands back as `nextCursor` and accepts as `cursor=`.

Scopes: `threads:read`.

**Parameters**

- `limit` (`int`): Threads per page, a whole number from 1 to 100. Defaults to 25.
- `cursor` (`str`): The `nextCursor` of the previous page, passed back unchanged.
- `folder` (`str`): Label the threads must carry, case insensitive. Defaults to `inbox`, and `bin` is read as `trash`.
- `query` (`str`): Mailbox search. Plain words must all appear and match loosely, a quoted phrase has to appear as written, filler words are dropped when something else is left to search for, and operators such as `from:ada`, `has:pdf` and `in:anywhere` narrow it.
- `label_ids` (`str | Sequence[str]`): Label ids a thread must all carry on top of `folder`, matched exactly. A list or tuple is sent comma separated, and a string is sent as it is.
- `sort` (`ThreadSort`): `newest` (the default), `oldest`, `sender` or `subject`, the four orders of the thread list in the app. `sender` and `subject` are alphabetical, newest first within one sender or subject.
- `date_from` (`datetime | str`): Keeps threads whose newest message arrived at or after this instant. A `datetime` or an ISO 8601 string with a time and an offset.
- `date_to` (`datetime | str`): Keeps threads whose newest message arrived at or before this instant. Both ends are included, and `date_from=` after `date_to=` is a 422.
- `from_contacts` (`bool`): When `True`, keeps only threads whose newest message came from a saved contact. A key limited to some addresses reads the contacts its owner saved.
- `semantic` (`bool`): When `True`, the plain words of `query` match by meaning instead of spelling, in any language, and the closest threads come first along with every thread the words match as text. Operators and the other filters still apply and `sort` does not. Ignored when the workspace has search by meaning turned off.
- `category` (`InboxCategory`): Keeps only the threads sorted into this inbox tab: `primary`, `promotions`, `updates`, `social` or `forums`, one of `INBOX_CATEGORIES`. `primary` is every thread in no other tab. In `query`, `category:promotions` filters the same way in any folder.
- `address` (`str`): Keeps only the threads delivered to this address, the address filter of the thread list. One the key does not reach returns nothing rather than failing.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`Page[ThreadSummaryResource]`, a dict with `items`, `hasMore` and `nextCursor`. Each item is a dict with `object` set to `thread` and the thread's `id`.

**Example**

```python
from datetime import datetime, timedelta, timezone

from nextmail import nextmail

page = nextmail.threads.list(folder='inbox', query='from:ada has:pdf', limit=50)
print([thread['id'] for thread in page['items']])

if page['hasMore'] and page['nextCursor']:
    following = nextmail.threads.list(
        folder='inbox', query='from:ada has:pdf', limit=50, cursor=page['nextCursor']
    )
    print(len(following['items']))

week_ago = datetime.now(timezone.utc) - timedelta(days=7)
oldest_first = nextmail.threads.list(sort='oldest', date_from=week_ago, from_contacts=True)
print(len(oldest_first['items']))

trip = nextmail.threads.list(folder='archive', query='flight to Berlin', semantic=True)

if trip['items']:
    print(trip['items'][0]['id'])

offers = nextmail.threads.list(category='promotions')
print(len(offers['items']))
```

**Notes**

- The server offers a cursor whenever a page comes back full, so `hasMore` can be `True` on what turns out to be the last page, and the next call then returns no items.
- Threads that arrived in the same instant are ordered by id, so a page boundary between two of them never skips or repeats one.
- A thread that receives mail while you page moves ahead of the cursor and is not returned by later pages.
- A value `query` cannot use is ignored rather than narrowing, so a typo in a value widens the result instead of emptying it. That covers `larger:`, `smaller:`, `size:`, `messagesize:`, `list:`, `rfc822msgid:`, `received:` and `sent:`, a `category:` naming no inbox tab, a `has:` word naming no kind of attachment, an `importance:` other than `high` or `low`, an unreadable date and a duration whose unit is not `h`, `d`, `w`, `m` or `y`. An operator name it does not know, `project:` for instance, is searched as plain text.
- A narrowed key only sees threads delivered to the addresses it covers, every address on a whole domain it holds included. A thread still has to carry the folder and every one of `label_ids=`, the same as for any other key.

Also available in: API [`GET /threads`](https://nextmail.sh/docs/api/reference/threads#get-threads); TypeScript [`threads.list()`](https://nextmail.sh/docs/sdk/reference/threads#list); Ruby [`threads.list`](https://nextmail.sh/docs/ruby/reference/threads#list); PHP [`threads->list`](https://nextmail.sh/docs/php/reference/threads#list); Go [`Threads.List`](https://nextmail.sh/docs/go/reference/threads#list); Java [`threads().list`](https://nextmail.sh/docs/java/reference/threads#list); C# [`Threads.ListAsync`](https://nextmail.sh/docs/csharp/reference/threads#list); CLI [`nextmail threads list`](https://nextmail.sh/docs/cli/reference/threads#threads-list).

### `threads.list_all()`

Collect every thread in a folder into one list

```python
def list_all(
    *,
    limit: int | None = None,
    cursor: str | None = None,
    folder: str | None = None,
    query: str | None = None,
    label_ids: str | Sequence[str] | None = None,
    sort: ThreadSort | None = None,
    date_from: datetime | str | None = None,
    date_to: datetime | str | None = None,
    from_contacts: bool | None = None,
    semantic: bool | None = None,
    category: InboxCategory | None = None,
    address: str | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[ThreadSummaryResource]
```

Walks every page with the same filters as `list` and returns once the last page is in, so the whole result sits in memory at once. That suits a label view or a small folder. For a large inbox, `iterate` lets you stop as soon as you have what you need.

Each request asks for `limit=` threads, 25 when you leave it out, so raising it to 100 needs a quarter of the round trips. Passing `cursor=` starts the walk from that page instead of the first. The walk ends when `hasMore` is `False`, when the server stops offering a cursor, or when it repeats one.

A failure on any page raises and discards everything collected so far.

Scopes: `threads:read`.

**Parameters**

- `limit` (`int`): Page size for each request, a whole number from 1 to 100. Defaults to 25.
- `cursor` (`str`): A `nextCursor` to start the walk from instead of the first page.
- `folder` (`str`): Label the threads must carry, case insensitive. Defaults to `inbox`.
- `query` (`str`): Mailbox search, as in `list`. Plain words must all appear and match loosely, a quoted phrase has to appear as written, filler words are dropped when something else is left to search for, and operators such as `from:ada`, `has:pdf` and `in:anywhere` narrow it.
- `label_ids` (`str | Sequence[str]`): Label ids a thread must all carry on top of `folder`, matched exactly.
- `sort` (`ThreadSort`): `newest` (the default), `oldest`, `sender` or `subject`, the four orders of the thread list in the app. `sender` and `subject` are alphabetical, newest first within one sender or subject.
- `date_from` (`datetime | str`): Keeps threads whose newest message arrived at or after this instant. A `datetime` or an ISO 8601 string with a time and an offset.
- `date_to` (`datetime | str`): Keeps threads whose newest message arrived at or before this instant. Both ends are included, and `date_from=` after `date_to=` is a 422.
- `from_contacts` (`bool`): When `True`, keeps only threads whose newest message came from a saved contact. A key limited to some addresses reads the contacts its owner saved.
- `semantic` (`bool`): When `True`, the plain words of `query` match by meaning instead of spelling, in any language, and the closest threads come first along with every thread the words match as text. Operators and the other filters still apply and `sort` does not. Ignored when the workspace has search by meaning turned off.
- `category` (`InboxCategory`): Keeps only the threads sorted into this inbox tab: `primary`, `promotions`, `updates`, `social` or `forums`, one of `INBOX_CATEGORIES`. `primary` is every thread in no other tab.
- `address` (`str`): Keeps only the threads delivered to this address, the address filter of the thread list. One the key does not reach returns nothing rather than failing.
- `api_key` (`str`): Overrides the client's API key for every page of this walk.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[ThreadSummaryResource]`, every matching thread as a dict with `object` and `id`, in the order `sort` asks for, newest first by default.

**Example**

```python
from nextmail import nextmail

snoozed = nextmail.threads.list_all(folder='snoozed', limit=100)

print(f'{len(snoozed)} threads are waiting to wake')
```

**Notes**

- Each page is its own request with its own retries, so a network blip on page five does not restart the walk from page one.
- Rows are ids only. Reading the threads afterwards is one `get` per id.

Also available in: API [`GET /threads`](https://nextmail.sh/docs/api/reference/threads#get-threads); TypeScript [`threads.listAll()`](https://nextmail.sh/docs/sdk/reference/threads#listAll); Ruby [`threads.list_all`](https://nextmail.sh/docs/ruby/reference/threads#listAll); PHP [`threads->listAll`](https://nextmail.sh/docs/php/reference/threads#listAll); Go [`Threads.ListAll`](https://nextmail.sh/docs/go/reference/threads#listAll); Java [`threads().listAll`](https://nextmail.sh/docs/java/reference/threads#listAll); C# [`Threads.ListAllAsync`](https://nextmail.sh/docs/csharp/reference/threads#listAll).

### `threads.iterate()`

Stream threads one at a time across pages

```python
def iterate(
    *,
    limit: int | None = None,
    cursor: str | None = None,
    folder: str | None = None,
    query: str | None = None,
    label_ids: str | Sequence[str] | None = None,
    sort: ThreadSort | None = None,
    date_from: datetime | str | None = None,
    date_to: datetime | str | None = None,
    from_contacts: bool | None = None,
    semantic: bool | None = None,
    category: InboxCategory | None = None,
    address: str | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> Iterator[ThreadSummaryResource]
```

Returns a generator that yields threads one by one and requests the next page only when the current one is used up. Nothing is fetched until the loop starts, and breaking out of it stops further requests, so this is the way to scan a large folder for the first match.

Filters behave as in `list`, and each request asks for `limit=` threads, 25 by default. The cursor marks a position in time rather than a row count, so trashing, archiving or relabelling threads inside the loop does not make the walk skip the ones after them. A thread that receives new mail during the walk moves ahead of the cursor and is not yielded again. With `semantic=True` the cursor counts places in the ranked list instead, so moving a thread out of the folder during the walk can shift the ones after it.

Scopes: `threads:read`.

**Parameters**

- `limit` (`int`): Page size for each request, a whole number from 1 to 100. Defaults to 25.
- `cursor` (`str`): A `nextCursor` to start from instead of the first page.
- `folder` (`str`): Label the threads must carry, case insensitive. Defaults to `inbox`.
- `query` (`str`): Mailbox search, as in `list`. Plain words must all appear and match loosely, a quoted phrase has to appear as written, filler words are dropped when something else is left to search for, and operators such as `from:ada`, `has:pdf` and `in:anywhere` narrow it.
- `label_ids` (`str | Sequence[str]`): Label ids a thread must all carry on top of `folder`, matched exactly.
- `sort` (`ThreadSort`): `newest` (the default), `oldest`, `sender` or `subject`, the four orders of the thread list in the app. `sender` and `subject` are alphabetical, newest first within one sender or subject.
- `date_from` (`datetime | str`): Keeps threads whose newest message arrived at or after this instant. A `datetime` or an ISO 8601 string with a time and an offset.
- `date_to` (`datetime | str`): Keeps threads whose newest message arrived at or before this instant. Both ends are included, and `date_from=` after `date_to=` is a 422.
- `from_contacts` (`bool`): When `True`, keeps only threads whose newest message came from a saved contact. A key limited to some addresses reads the contacts its owner saved.
- `semantic` (`bool`): When `True`, the plain words of `query` match by meaning instead of spelling, in any language, and the closest threads come first along with every thread the words match as text. Operators and the other filters still apply and `sort` does not. Ignored when the workspace has search by meaning turned off.
- `category` (`InboxCategory`): Keeps only the threads sorted into this inbox tab: `primary`, `promotions`, `updates`, `social` or `forums`, one of `INBOX_CATEGORIES`. `primary` is every thread in no other tab.
- `address` (`str`): Keeps only the threads delivered to this address, the address filter of the thread list. One the key does not reach returns nothing rather than failing.
- `api_key` (`str`): Overrides the client's API key for every page of this walk.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`Iterator[ThreadSummaryResource]`, a generator yielding a dict with `object` and `id` per step.

**Example**

```python
from nextmail import nextmail

receipts = nextmail.threads.iterate(folder='inbox', query='receipt newer_than:30d', limit=100)

for summary in receipts:
    thread = nextmail.threads.get(summary['id'])

    if thread['hasUnread']:
        nextmail.threads.update(summary['id'], {'read': True})
```

**Notes**

- The generator is lazy, so an abandoned loop costs only the pages it consumed.
- `timeout=` applies to each page's request. A page that still times out after the SDK's retries raises `NextmailNetworkError` with `is_timeout` out of the loop rather than ending it quietly.

Also available in: API [`GET /threads`](https://nextmail.sh/docs/api/reference/threads#get-threads); TypeScript [`threads.iterate()`](https://nextmail.sh/docs/sdk/reference/threads#iterate); Ruby [`threads.iterate`](https://nextmail.sh/docs/ruby/reference/threads#iterate); PHP [`threads->iterate`](https://nextmail.sh/docs/php/reference/threads#iterate); Go [`Threads.Iterate`](https://nextmail.sh/docs/go/reference/threads#iterate); Java [`threads().iterate`](https://nextmail.sh/docs/java/reference/threads#iterate); C# [`Threads.IterateAsync`](https://nextmail.sh/docs/csharp/reference/threads#iterate).

### `threads.get()`

Read a thread with every message on it

```python
def get(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadResource
```

Returns the whole conversation, oldest message first, with the labels the thread sits in and its unread state. Unsent draft replies are included in `messages` with `'isDraft': True`, which is why `messageCount`, the length of `messages`, can be higher than `totalReplies`, which counts only real messages.

Messages are passed through as the mailbox stored them, so `MessageResource` is a plain `dict[str, Any]` rather than a fixed field list. The one key the API commits to is `encryption`. When `message['encryption']['format']` is `pgp-mime`, `pgp-inline` or `smime-encrypted`, the message is sealed and its body is empty or holds armour, and `is_sealed(message)` from `nextmail` returns `True`. `pgp-signed` and `smime-signed` are ordinary readable mail. A message with no `encryption` at all was stored before detection existed, so its absence says nothing about whether it was plaintext.

Each message's `tags` and `unread` are overwritten on read with the thread's current labels and unread flag, so they describe the thread and not that one message.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id, as returned by `list` or carried on a message.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadResource` with `id` echoed from the request, `messages`, `labels` (each with `id`, `name` and `color`), `messageCount`, `hasUnread`, `totalReplies` and `deliveredTo`, the workspace address the thread belongs to (`None` when none was recorded).

**Example**

```python
from nextmail import is_sealed, nextmail

thread = nextmail.threads.get('thr_8f2c41d0a3b94e6f')

for message in thread['messages']:
    state = 'sealed' if is_sealed(message) else 'readable'
    print(message.get('id'), message.get('subject'), state)

print([label['id'] for label in thread['labels']], thread['deliveredTo'])
```

**Notes**

- A thread delivered to no address the key covers is a 404, exactly like one that does not exist.
- `hasUnread` mirrors the `UNREAD` label, and `update` with `read` is how you change it.
- Draft ids from `drafts.list` open here too, because a draft is stored as a thread labelled `DRAFT`.

Also available in: API [`GET /threads/{id}`](https://nextmail.sh/docs/api/reference/threads#get-threads-id); TypeScript [`threads.get()`](https://nextmail.sh/docs/sdk/reference/threads#get); Ruby [`threads.get`](https://nextmail.sh/docs/ruby/reference/threads#get); PHP [`threads->get`](https://nextmail.sh/docs/php/reference/threads#get); Go [`Threads.Get`](https://nextmail.sh/docs/go/reference/threads#get); Java [`threads().get`](https://nextmail.sh/docs/java/reference/threads#get); C# [`Threads.GetAsync`](https://nextmail.sh/docs/csharp/reference/threads#get); CLI [`nextmail threads get`](https://nextmail.sh/docs/cli/reference/threads#threads-get).

### `threads.update()`

Mark a thread read or unread and change its labels

```python
def update(
    id: str,
    patch: ThreadPatch,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> UpdatedThreadResource
```

Adds and removes labels on a thread in one call. `read` is shorthand for the `UNREAD` label: `True` removes it and `False` adds it. At least one of `read`, a non empty `addLabelIds` or a non empty `removeLabelIds` is required, each list takes at most 50 ids, and any other key is a 422 because the body is strict.

Folders are labels too, so archiving is `{'addLabelIds': ['ARCHIVE'], 'removeLabelIds': ['INBOX']}`, the same pair the app uses. `TRASH`, `SNOOZED` and `DRAFT` are refused in either list with 422 `label_not_directly_settable`, because each needs a step this route cannot take. Use `trash` and `snooze` for those.

User label ids come from `labels.list`, and the system ids such as `ARCHIVE`, `STARRED` and `UNREAD` are taken in any case. An id in `addLabelIds` that names no label is refused with 422 `label_not_found` and nothing on the thread changes, so create the label with `labels.create` first. An unknown id in `removeLabelIds` is not an error, since the thread cannot carry it. Removals are applied before additions, so an id in both lists ends up on the thread.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `patch['read']` (`bool`): `True` removes `UNREAD`, `False` adds it.
- `patch['addLabelIds']` (`list[str]`): Label ids to put on the thread, at most 50, each naming a label, never `TRASH`, `SNOOZED` or `DRAFT`.
- `patch['removeLabelIds']` (`list[str]`): Label ids to take off the thread, at most 50, never `TRASH`, `SNOOZED` or `DRAFT`.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`UpdatedThreadResource` with `id`, `addedLabelIds` and `removedLabelIds`. Both lists echo the request, with system ids upper cased, plus the `UNREAD` change that `read` implies, not what actually changed.

**Example**

```python
from nextmail import nextmail

updated = nextmail.threads.update(
    'thr_8f2c41d0a3b94e6f',
    {'read': True, 'addLabelIds': ['ARCHIVE', 'USER_RECEIPTS'], 'removeLabelIds': ['INBOX']},
)

print(updated['addedLabelIds'], updated['removedLabelIds'])
```

**Notes**

- The SDK retries this call after a network failure or a retryable status, which is safe because adding a label already present or removing one already gone changes nothing.
- The thread is looked up before the body is validated, so a wrong id is a 404 even when the patch is also invalid.
- User label ids look like `USER_RECEIPTS`. Take them from `labels.list` rather than building them.

Also available in: API [`PATCH /threads/{id}`](https://nextmail.sh/docs/api/reference/threads#patch-threads-id); TypeScript [`threads.update()`](https://nextmail.sh/docs/sdk/reference/threads#update); Ruby [`threads.update`](https://nextmail.sh/docs/ruby/reference/threads#update); PHP [`threads->update`](https://nextmail.sh/docs/php/reference/threads#update); Go [`Threads.Update`](https://nextmail.sh/docs/go/reference/threads#update); Java [`threads().update`](https://nextmail.sh/docs/java/reference/threads#update); C# [`Threads.UpdateAsync`](https://nextmail.sh/docs/csharp/reference/threads#update); CLI [`nextmail threads update`](https://nextmail.sh/docs/cli/reference/threads#threads-update).

### `threads.trash()`

Move a thread to the Bin

```python
def trash(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> TrashedThreadResource
```

Adds `TRASH` and removes `INBOX`, `SPAM`, `SNOOZED` and `ARCHIVE` in one step, which is what the app's delete does. Doing half of that through `update` would leave the thread listed in both the Bin and its old folder, which is why `update` refuses `TRASH`.

Nothing is deleted. The thread stays readable with `get` and lists under `folder='trash'`. Calling this on a thread that is already in the Bin changes nothing and returns the same body, which is why the SDK retries it.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`TrashedThreadResource` with `object` set to `thread`, the `id`, and `trashed` set to `True`.

**Example**

```python
from nextmail import NextmailApiError, nextmail

try:
    result = nextmail.threads.trash('thr_8f2c41d0a3b94e6f')
except NextmailApiError as error:
    if not error.is_not_found:
        raise
    print('No such thread, or the key does not reach it')
else:
    print(result['id'], result['trashed'])
```

**Notes**

- `restore` takes a thread back out of the Bin. `update` refuses `TRASH` in `removeLabelIds` as well as in `addLabelIds`.
- Trashing a snoozed thread also cancels its scheduled wake, so it does not reappear in the inbox later.
- A thread delivered to no address the key covers is a 404.

Also available in: API [`POST /threads/{id}/trash`](https://nextmail.sh/docs/api/reference/threads#post-threads-id-trash); TypeScript [`threads.trash()`](https://nextmail.sh/docs/sdk/reference/threads#trash); Ruby [`threads.trash`](https://nextmail.sh/docs/ruby/reference/threads#trash); PHP [`threads->trash`](https://nextmail.sh/docs/php/reference/threads#trash); Go [`Threads.Trash`](https://nextmail.sh/docs/go/reference/threads#trash); Java [`threads().trash`](https://nextmail.sh/docs/java/reference/threads#trash); C# [`Threads.TrashAsync`](https://nextmail.sh/docs/csharp/reference/threads#trash); CLI [`nextmail threads trash`](https://nextmail.sh/docs/cli/reference/threads#threads-trash).

### `threads.snooze()`

Hide a thread until a set time

```python
def snooze(
    id: str,
    wake_at: datetime | str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> SnoozedThreadResource
```

Adds `SNOOZED`, removes `INBOX` and stores a wake time, all in one call. Both halves matter: the label hides the thread and the stored wake time is what brings it back. A thread labelled `SNOOZED` any other way would never return, which is why `update` refuses that label.

`wake_at` takes a `datetime` or an ISO 8601 string. The SDK sends a `datetime` as a UTC ISO 8601 string, and the server answers 422 `invalid_parameter` on `wakeAt` when the value does not parse or is not in the future. Snoozing a thread that is already snoozed replaces its wake time.

Threads are woken by an hourly sweep, so one comes back at the first sweep after `wake_at`, up to about an hour late. Opening the Snoozed folder in the app wakes overdue threads straight away. A thread always wakes into the inbox.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `wake_at` (`datetime | str`, required): When the thread should return, a future instant.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`SnoozedThreadResource` with `id` and `snoozedUntil`, the wake time normalised to a UTC ISO string.

**Example**

```python
from datetime import datetime, timedelta, timezone

from nextmail import nextmail

tomorrow = datetime.now(timezone.utc) + timedelta(days=1)
wake_at = tomorrow.replace(hour=9, minute=0, second=0, microsecond=0)

snoozed = nextmail.threads.snooze('thr_8f2c41d0a3b94e6f', wake_at)
print(snoozed['snoozedUntil'])
```

**Notes**

- Only `INBOX` is removed, so a thread snoozed from another folder keeps that folder's label while it sleeps and wakes carrying both.
- A string with no zone offset is read in the server's local zone, so send `Z` or an explicit offset. A naive `datetime` is read in the local zone of the machine running the SDK, so give it a `tzinfo`.
- The SDK retries this call, which is safe because a repeat stores the same wake time.

Also available in: API [`POST /threads/{id}/snooze`](https://nextmail.sh/docs/api/reference/threads#post-threads-id-snooze); TypeScript [`threads.snooze()`](https://nextmail.sh/docs/sdk/reference/threads#snooze); Ruby [`threads.snooze`](https://nextmail.sh/docs/ruby/reference/threads#snooze); PHP [`threads->snooze`](https://nextmail.sh/docs/php/reference/threads#snooze); Go [`Threads.Snooze`](https://nextmail.sh/docs/go/reference/threads#snooze); Java [`threads().snooze`](https://nextmail.sh/docs/java/reference/threads#snooze); C# [`Threads.SnoozeAsync`](https://nextmail.sh/docs/csharp/reference/threads#snooze); CLI [`nextmail threads snooze`](https://nextmail.sh/docs/cli/reference/threads#threads-snooze).

### `threads.unsnooze()`

Bring a snoozed thread back now

```python
def unsnooze(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> SnoozedThreadResource
```

Adds `INBOX`, removes `SNOOZED` and deletes the stored wake time, so the thread returns immediately and the hourly sweep leaves it alone afterwards.

A thread that is not snoozed is left where it is, so an archived thread stays archived, and the response still reports `snoozedUntil` as `None`.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`SnoozedThreadResource` with `id` and `snoozedUntil` set to `None`.

**Example**

```python
from nextmail import nextmail

for summary in nextmail.threads.iterate(folder='snoozed'):
    result = nextmail.threads.unsnooze(summary['id'])
    print('back in the inbox:', result['id'])
```

**Notes**

- Removing `SNOOZED` through `update` is refused with 422 `label_not_directly_settable`, because it would leave the wake time scheduled.
- Safe to retry, and the SDK does: a second call applies the same labels and deletes a wake time that is already gone.

Also available in: API [`POST /threads/{id}/unsnooze`](https://nextmail.sh/docs/api/reference/threads#post-threads-id-unsnooze); TypeScript [`threads.unsnooze()`](https://nextmail.sh/docs/sdk/reference/threads#unsnooze); Ruby [`threads.unsnooze`](https://nextmail.sh/docs/ruby/reference/threads#unsnooze); PHP [`threads->unsnooze`](https://nextmail.sh/docs/php/reference/threads#unsnooze); Go [`Threads.Unsnooze`](https://nextmail.sh/docs/go/reference/threads#unsnooze); Java [`threads().unsnooze`](https://nextmail.sh/docs/java/reference/threads#unsnooze); C# [`Threads.UnsnoozeAsync`](https://nextmail.sh/docs/csharp/reference/threads#unsnooze); CLI [`nextmail threads unsnooze`](https://nextmail.sh/docs/cli/reference/threads#threads-unsnooze).

### `threads.mute()`

Mute a thread

```python
def mute(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> MutedThreadResource
```

Mutes a conversation, as Mute does in the app. A thread in the inbox moves to the archive, and from then on new mail in it goes straight to the archive, unread, with no push, sound or desktop notice. A webhook for that mail carries `muted` set to `True`.

Thread state belongs to the whole workspace, so the thread is muted for everyone on it, and mail addressed only to you does not bring it back. Calling it again changes nothing, which is why the SDK retries it. `update` with `MUTE` in `addLabelIds` does the same.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`MutedThreadResource` with `object` set to `thread`, the `id`, and `muted` set to `True`.

**Example**

```python
from nextmail import nextmail

muted = nextmail.threads.mute('thr_8f2c41d0a3b94e6f')

print(muted['id'], muted['muted'])
```

**Notes**

- Only a thread in the inbox moves. One in Sent, the archive or Snoozed stays where it is.
- A muted thread carries the built-in `MUTE` label, which `get` shows among its labels and `is:muted` finds in `query`.
- `unmute` takes the mute off. A thread delivered to no address the key covers is a 404.

Also available in: API [`POST /threads/{id}/mute`](https://nextmail.sh/docs/api/reference/threads#post-threads-id-mute); TypeScript [`threads.mute()`](https://nextmail.sh/docs/sdk/reference/threads#mute); Ruby [`threads.mute`](https://nextmail.sh/docs/ruby/reference/threads#mute); PHP [`threads->mute`](https://nextmail.sh/docs/php/reference/threads#mute); Go [`Threads.Mute`](https://nextmail.sh/docs/go/reference/threads#mute); Java [`threads().mute`](https://nextmail.sh/docs/java/reference/threads#mute); C# [`Threads.MuteAsync`](https://nextmail.sh/docs/csharp/reference/threads#mute); CLI [`nextmail threads mute`](https://nextmail.sh/docs/cli/reference/threads#threads-mute).

### `threads.unmute()`

Take the mute off a thread

```python
def unmute(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> MutedThreadResource
```

Takes the mute off, so the next message in the thread arrives in the inbox and alerts people again.

The thread stays where it is. Move it back with `update` and `INBOX` in `addLabelIds` if you want it in the inbox now. A thread that is not muted is left as it is, which is why the SDK retries this call.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`MutedThreadResource` with `object` set to `thread`, the `id`, and `muted` set to `False`.

**Example**

```python
from nextmail import nextmail

result = nextmail.threads.unmute('thr_8f2c41d0a3b94e6f')

print(result['id'], result['muted'])
```

**Notes**

- Unmuting is for the whole workspace, as muting is: the thread alerts everyone on it again.
- A thread delivered to no address the key covers is a 404.

Also available in: API [`POST /threads/{id}/unmute`](https://nextmail.sh/docs/api/reference/threads#post-threads-id-unmute); TypeScript [`threads.unmute()`](https://nextmail.sh/docs/sdk/reference/threads#unmute); Ruby [`threads.unmute`](https://nextmail.sh/docs/ruby/reference/threads#unmute); PHP [`threads->unmute`](https://nextmail.sh/docs/php/reference/threads#unmute); Go [`Threads.Unmute`](https://nextmail.sh/docs/go/reference/threads#unmute); Java [`threads().unmute`](https://nextmail.sh/docs/java/reference/threads#unmute); C# [`Threads.UnmuteAsync`](https://nextmail.sh/docs/csharp/reference/threads#unmute); CLI [`nextmail threads unmute`](https://nextmail.sh/docs/cli/reference/threads#threads-unmute).

### `threads.list_messages()`

List the messages of a thread in a fixed shape

```python
def list_messages(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[MailboxMessageResource]
```

Returns every message on the thread, oldest first, as `MailboxMessageResource`: `from`, `to`, `cc`, `bcc` and `replyTo` as `{'name': ..., 'email': ...}`, `date` as an ISO 8601 instant, `messageId`, `inReplyTo` and `references`, the body as `text` and `html`, the `attachments` without their bytes, the `headers` Nextmail keeps and `encryption`. Unsent draft replies are in the list with `draft` set to `True`.

These fields are a contract: they are added to, never renamed or taken away, whatever the mailbox stores underneath. `threads.get` still returns each message the way the mailbox stored it, so use this when your code reads messages field by field.

`text` is the plain text body, or the text drawn from the HTML when the message came as HTML only. `html` is `None` for a plain text message. `headers` holds From, To, Cc, Reply-To, Subject, Date, Message-ID, In-Reply-To, References, List-Unsubscribe and List-Unsubscribe-Post when the message had them, and nothing else, because the rest of what it arrived with is not kept.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id, as returned by `list`.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[MailboxMessageResource]`, oldest first.

**Example**

```python
from nextmail import nextmail

messages = nextmail.threads.list_messages('thr_8f2c41d0a3b94e6f')

for message in messages:
    print(message['date'], message['from']['email'], message['subject'])
    print((message['text'] or '')[:200])
```

**Notes**

- A thread delivered to no address the key covers is a 404, exactly like one that does not exist.
- Read an attachment's bytes with `list_attachments(id, message['id'])`.

Also available in: API [`GET /threads/{id}/messages`](https://nextmail.sh/docs/api/reference/threads#get-threads-id-messages); TypeScript [`threads.listMessages()`](https://nextmail.sh/docs/sdk/reference/threads#listMessages); Ruby [`threads.list_messages`](https://nextmail.sh/docs/ruby/reference/threads#listMessages); PHP [`threads->listMessages`](https://nextmail.sh/docs/php/reference/threads#listMessages); Go [`Threads.ListMessages`](https://nextmail.sh/docs/go/reference/threads#listMessages); Java [`threads().listMessages`](https://nextmail.sh/docs/java/reference/threads#listMessages); C# [`Threads.ListMessagesAsync`](https://nextmail.sh/docs/csharp/reference/threads#listMessages); CLI [`nextmail threads list-messages`](https://nextmail.sh/docs/cli/reference/threads#threads-list-messages).

### `threads.get_message()`

Read one message of a thread in a fixed shape

```python
def get_message(
    id: str,
    message_id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> MailboxMessageResource
```

Returns one message as `MailboxMessageResource`, the shape `list_messages` lists. The thread is checked first and then the message, so a `message_id` that is not on that thread is a 404 even when it exists elsewhere in the mailbox.

The `emailId` of an `email.received` webhook is the `message_id` to pass here, beside its `threadId`.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id the message belongs to.
- `message_id` (`str`, required): The message, as `id` on a message `list_messages` returns.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`MailboxMessageResource`.

**Example**

```python
from nextmail import nextmail

message = nextmail.threads.get_message('thr_8f2c41d0a3b94e6f', 'msg_3f9a1c07d2b84e6a9c5b1f20')

print(message['from'], message['date'])
print([file['filename'] for file in message['attachments']])
```

**Notes**

- Both ids must match: a real message id paired with the wrong thread id is a 404 `resource_not_found`.
- A thread delivered to no address the key covers is a 404 before the message is looked at.

Also available in: API [`GET /threads/{id}/messages/{messageId}`](https://nextmail.sh/docs/api/reference/threads#get-threads-id-messages-messageid); TypeScript [`threads.getMessage()`](https://nextmail.sh/docs/sdk/reference/threads#getMessage); Ruby [`threads.get_message`](https://nextmail.sh/docs/ruby/reference/threads#getMessage); PHP [`threads->getMessage`](https://nextmail.sh/docs/php/reference/threads#getMessage); Go [`Threads.GetMessage`](https://nextmail.sh/docs/go/reference/threads#getMessage); Java [`threads().getMessage`](https://nextmail.sh/docs/java/reference/threads#getMessage); C# [`Threads.GetMessageAsync`](https://nextmail.sh/docs/csharp/reference/threads#getMessage); CLI [`nextmail threads get-message`](https://nextmail.sh/docs/cli/reference/threads#threads-get-message).

### `threads.get_raw_message()`

Download the source of a message

```python
def get_raw_message(
    id: str,
    message_id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> bytes
```

Returns the whole message as `message/rfc822` bytes, its headers and its MIME body, ready to write to an `.eml` file, open in a mail app or hand to a parser such as `email.message_from_bytes`. When the address had `keepOriginal` on as the message arrived, these are the bytes exactly as they arrived. Otherwise the source is rebuilt from the stored message, the same bytes the IMAP server gives a mail app, with the addresses, the subject, the threading headers, the text and HTML and every attachment. The `X-Message-Source` header of the response says which, `original` or `rebuilt`, one of `RAW_MESSAGE_SOURCES`, but the method returns only the bytes.

The thread is checked first and then the message, as in `get_message`.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id the message belongs to.
- `message_id` (`str`, required): The message, as `id` on a message `list_messages` returns or `emailId` in an `email.received` webhook.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`bytes` holding the message source.

**Example**

```python
from pathlib import Path

from nextmail import nextmail

source = nextmail.threads.get_raw_message(
    'thr_8f2c41d0a3b94e6f', 'msg_3f9a1c07d2b84e6a9c5b1f20'
)

Path('message.eml').write_bytes(source)
print('Saved', len(source), 'bytes')
```

**Notes**

- The whole message is held in memory, so fetch very large ones one at a time.
- A rebuilt source carries none of the headers the message arrived with beyond the ones it is built from, so a DKIM signature cannot be checked against it. Turn on `keepOriginal` for the address with `domains.update_address` before the mail arrives when you need the exact bytes.
- Both ids must match: a real message id paired with the wrong thread id is a 404 `resource_not_found`, and so is a thread delivered to no address the key covers.

Also available in: API [`GET /threads/{id}/messages/{messageId}/raw`](https://nextmail.sh/docs/api/reference/threads#get-threads-id-messages-messageid-raw); TypeScript [`threads.getRawMessage()`](https://nextmail.sh/docs/sdk/reference/threads#getRawMessage); Ruby [`threads.get_raw_message`](https://nextmail.sh/docs/ruby/reference/threads#getRawMessage); PHP [`threads->getRawMessage`](https://nextmail.sh/docs/php/reference/threads#getRawMessage); Go [`Threads.GetRawMessage`](https://nextmail.sh/docs/go/reference/threads#getRawMessage); Java [`threads().getRawMessage`](https://nextmail.sh/docs/java/reference/threads#getRawMessage); C# [`Threads.GetRawMessageAsync`](https://nextmail.sh/docs/csharp/reference/threads#getRawMessage); CLI [`nextmail threads get-raw-message`](https://nextmail.sh/docs/cli/reference/threads#threads-get-raw-message).

### `threads.list_attachments()`

List a message's attachments with their content

```python
def list_attachments(
    id: str,
    message_id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[AttachmentResource]
```

Returns the attachments of one message with each file's bytes inlined as base64 in `content`, which `base64.b64decode` turns back into `bytes`. The thread is checked first and then the message, so a `message_id` that is not on that thread is a 404 even when it exists elsewhere in the mailbox. Take message ids from the `messages` of `threads.get`.

This is the display list. The ciphertext of an encrypted envelope is in it and downloads like any other file, named `encrypted-message.asc` when it arrived without a name. The PGP/MIME version part and any detached signature are held out on purpose. Every part keeps its id in the message's `encryption['parts']`, and for those two the id is a correlation key only: no route returns their bytes.

Every file comes back whole in a single response, with no size cap and no range reads, so a message carrying large files makes a large response.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id the message belongs to.
- `message_id` (`str`, required): Message id from that thread's `messages`.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[AttachmentResource]`, each with `attachmentId`, `filename`, `contentType`, `size` and base64 `content`.

**Example**

```python
import base64

from nextmail import nextmail

files = nextmail.threads.list_attachments(
    'thr_8f2c41d0a3b94e6f', 'msg_3f9a1c07d2b84e6a9c5b1f20'
)

for file in files:
    data = base64.b64decode(file['content'] or '')
    print(file['filename'], file['contentType'], len(data))
```

**Notes**

- When the stored bytes for a file cannot be found, `content` is an empty string rather than `None`, so check its length before decoding.
- Both ids must match: a real message id paired with the wrong thread id is a 404 `resource_not_found`.
- A thread delivered to no address the key covers is a 404 before the message is looked at.

Also available in: API [`GET /threads/{id}/messages/{messageId}/attachments`](https://nextmail.sh/docs/api/reference/threads#get-threads-id-messages-messageid-attachments); TypeScript [`threads.listAttachments()`](https://nextmail.sh/docs/sdk/reference/threads#listAttachments); Ruby [`threads.list_attachments`](https://nextmail.sh/docs/ruby/reference/threads#listAttachments); PHP [`threads->listAttachments`](https://nextmail.sh/docs/php/reference/threads#listAttachments); Go [`Threads.ListAttachments`](https://nextmail.sh/docs/go/reference/threads#listAttachments); Java [`threads().listAttachments`](https://nextmail.sh/docs/java/reference/threads#listAttachments); C# [`Threads.ListAttachmentsAsync`](https://nextmail.sh/docs/csharp/reference/threads#listAttachments); CLI [`nextmail threads list-attachments`](https://nextmail.sh/docs/cli/reference/threads#threads-list-attachments).

### `threads.list_file_links()`

List the download links one message carries

```python
def list_file_links(
    id: str,
    message_id: str,
    *,
    limit: int | None = None,
    cursor: str | None = None,
    include_revoked: bool | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> Page[FileLinkResource]
```

Returns one page of the files one message sent as download links rather than inside it, newest first, as the app lists them under a message it sent: each link with how often it was fetched and when last. `list_all_file_links` collects every page and `iterate_file_links` walks them lazily.

A large attachment goes out as a link of its own on every send, so this is the copy of each file this message carried, while `files.list_links` lists every link one file ever had. A file attached inside the message has no link and is not listed, because nothing records when those are opened.

The thread is checked first and then the message, as `get_message` does, so a message that is not on that thread is a 404 even when it exists elsewhere in the mailbox. A key or an app limited to particular addresses sees only the links of the files that belong to the addresses it covers.

Scopes: `files:read`.

**Parameters**

- `id` (`str`, required): Thread id the message belongs to.
- `message_id` (`str`, required): Message id from that thread's `messages`, or its Message-ID header.
- `limit` (`int`): Page size, from 1 to 100. The server defaults to 25.
- `cursor` (`str`): The `nextCursor` of the previous page. Leave it out for the first page.
- `include_revoked` (`bool`): `True` lists the links that were revoked too, each with its `revokedAt`, as the app does. Left out, only the links that still work.
- `api_key` (`str`): Overrides the client API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`Page[FileLinkResource]`, a dict with `items`, `hasMore` and `nextCursor`. Each item has `id`, `url`, `host`, `downloads`, `lastDownloadAt`, `revokedAt` and `createdAt`.

**Example**

```python
from nextmail import nextmail

page = nextmail.threads.list_file_links(
    'thr_8f2c41d0a3b94e6f', 'msg_3f9a1c07d2b84e6a9c5b1f20', include_revoked=True
)

for link in page['items']:
    print(link['url'], link['downloads'], link['revokedAt'])
```

**Notes**

- The count leaves out scanners and link previewers, the same classifier the `email.downloaded` webhook uses.
- A thread delivered to no address the key covers, or a message that is not on it, is a 404.

Also available in: API [`GET /threads/{id}/messages/{messageId}/file-links`](https://nextmail.sh/docs/api/reference/files#get-threads-id-messages-messageid-file-links); TypeScript [`threads.listFileLinks()`](https://nextmail.sh/docs/sdk/reference/threads#listFileLinks); Ruby [`threads.list_file_links`](https://nextmail.sh/docs/ruby/reference/threads#listFileLinks); PHP [`threads->listFileLinks`](https://nextmail.sh/docs/php/reference/threads#listFileLinks); Go [`Threads.ListFileLinks`](https://nextmail.sh/docs/go/reference/threads#listFileLinks); Java [`threads().listFileLinks`](https://nextmail.sh/docs/java/reference/threads#listFileLinks); C# [`Threads.ListFileLinksAsync`](https://nextmail.sh/docs/csharp/reference/threads#listFileLinks); CLI [`nextmail threads list-file-links`](https://nextmail.sh/docs/cli/reference/threads#threads-list-file-links).

### `threads.list_all_file_links()`

Collect every download link of a message into one list

```python
def list_all_file_links(
    id: str,
    message_id: str,
    *,
    limit: int | None = None,
    cursor: str | None = None,
    include_revoked: bool | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[FileLinkResource]
```

Walks every page of `list_file_links` and returns every download link the message carries in one list, newest first. One request per page, with the same filters on each.

Scopes: `files:read`.

**Parameters**

- `id` (`str`, required): Thread id the message belongs to.
- `message_id` (`str`, required): Message id from that thread's `messages`, or its Message-ID header.
- `limit` (`int`): Page size for each request, from 1 to 100. The server defaults to 25.
- `cursor` (`str`): Starts the walk after this cursor instead of the first page.
- `include_revoked` (`bool`): `True` lists the links that were revoked too. Left out, only the links that still work.
- `api_key` (`str`): Overrides the client API key for every page of this walk.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[FileLinkResource]` holding every download link of the message.

**Example**

```python
from nextmail import nextmail

links = nextmail.threads.list_all_file_links(
    'thr_8f2c41d0a3b94e6f', 'msg_3f9a1c07d2b84e6a9c5b1f20'
)

print(sum(link['downloads'] for link in links), 'downloads in all')
```

**Notes**

- If any page fails, the call raises and the rows already fetched are discarded.

Also available in: API [`GET /threads/{id}/messages/{messageId}/file-links`](https://nextmail.sh/docs/api/reference/files#get-threads-id-messages-messageid-file-links); TypeScript [`threads.listAllFileLinks()`](https://nextmail.sh/docs/sdk/reference/threads#listAllFileLinks); Ruby [`threads.list_all_file_links`](https://nextmail.sh/docs/ruby/reference/threads#listAllFileLinks); PHP [`threads->listAllFileLinks`](https://nextmail.sh/docs/php/reference/threads#listAllFileLinks); Go [`Threads.ListAllFileLinks`](https://nextmail.sh/docs/go/reference/threads#listAllFileLinks); Java [`threads().listAllFileLinks`](https://nextmail.sh/docs/java/reference/threads#listAllFileLinks); C# [`Threads.ListAllFileLinksAsync`](https://nextmail.sh/docs/csharp/reference/threads#listAllFileLinks).

### `threads.iterate_file_links()`

Stream the download links of a message one at a time

```python
def iterate_file_links(
    id: str,
    message_id: str,
    *,
    limit: int | None = None,
    cursor: str | None = None,
    include_revoked: bool | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> Iterator[FileLinkResource]
```

Returns a generator that yields one link at a time, newest first, and requests the next page only once the current one is drained. Nothing is fetched until you loop over it, and breaking out of the loop stops the requests.

Scopes: `files:read`.

**Parameters**

- `id` (`str`, required): Thread id the message belongs to.
- `message_id` (`str`, required): Message id from that thread's `messages`, or its Message-ID header.
- `limit` (`int`): Page size for each request, from 1 to 100. The server defaults to 25.
- `cursor` (`str`): Starts the walk after this cursor instead of the first page.
- `include_revoked` (`bool`): `True` lists the links that were revoked too. Left out, only the links that still work.
- `api_key` (`str`): Overrides the client API key for every page of this walk.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`Iterator[FileLinkResource]`, a generator yielding one link per step.

**Example**

```python
from nextmail import nextmail

for link in nextmail.threads.iterate_file_links(
    'thr_8f2c41d0a3b94e6f', 'msg_3f9a1c07d2b84e6a9c5b1f20'
):
    print(link['url'], link['lastDownloadAt'])
```

**Notes**

- Each page is one request, so a long walk makes many.

Also available in: API [`GET /threads/{id}/messages/{messageId}/file-links`](https://nextmail.sh/docs/api/reference/files#get-threads-id-messages-messageid-file-links); TypeScript [`threads.iterateFileLinks()`](https://nextmail.sh/docs/sdk/reference/threads#iterateFileLinks); Ruby [`threads.iterate_file_links`](https://nextmail.sh/docs/ruby/reference/threads#iterateFileLinks); PHP [`threads->iterateFileLinks`](https://nextmail.sh/docs/php/reference/threads#iterateFileLinks); Go [`Threads.IterateFileLinks`](https://nextmail.sh/docs/go/reference/threads#iterateFileLinks); Java [`threads().iterateFileLinks`](https://nextmail.sh/docs/java/reference/threads#iterateFileLinks); C# [`Threads.IterateFileLinksAsync`](https://nextmail.sh/docs/csharp/reference/threads#iterateFileLinks).

### `threads.list_tracking()`

Read how the mail sent in a thread was read

```python
def list_tracking(
    id: str,
    *,
    address: str | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[TrackingResource]
```

Returns every tracked message this workspace sent in the thread, newest first, each the whole report `tracking.get` serves: the counts of each recipient and every rewritten link with its clicks. It is what the app shows under a message it sent.

A message that went out with tracking off is not in the list, so an empty list means nothing in the thread was tracked, not that nobody read it. A key or an app limited to particular addresses sees only the messages sent from the addresses it covers.

Scopes: `emails:read`.

**Parameters**

- `id` (`str`, required): Thread id.
- `address` (`str`): Keeps only the messages sent from this address, the address filter of the tracking page. One the key does not reach lists nothing rather than failing.
- `api_key` (`str`): Reads with this key instead of the client's.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[TrackingResource]`, newest first, each with `id`, `sendId`, `threadId`, `subject`, `from`, `sentAt`, `opens`, `clicks`, `opened`, `clicked`, `attributable`, counted and raw open and click counts, `recipients` and `links`.

**Example**

```python
from nextmail import nextmail

reports = nextmail.threads.list_tracking('CAHk7pQ2x9LmZ4-mail.example.com')

for report in reports:
    print(report['subject'], report['opened'], report['openCount'])
```

**Notes**

- Read every count as a floor: an open is inferred from a mail client fetching an image, so a reader whose client blocks images is never counted.

Also available in: API [`GET /threads/{id}/tracking`](https://nextmail.sh/docs/api/reference/tracking#get-threads-id-tracking); TypeScript [`threads.listTracking()`](https://nextmail.sh/docs/sdk/reference/threads#listTracking); Ruby [`threads.list_tracking`](https://nextmail.sh/docs/ruby/reference/threads#listTracking); PHP [`threads->listTracking`](https://nextmail.sh/docs/php/reference/threads#listTracking); Go [`Threads.ListTracking`](https://nextmail.sh/docs/go/reference/threads#listTracking); Java [`threads().listTracking`](https://nextmail.sh/docs/java/reference/threads#listTracking); C# [`Threads.ListTrackingAsync`](https://nextmail.sh/docs/csharp/reference/threads#listTracking); CLI [`nextmail threads list-tracking`](https://nextmail.sh/docs/cli/reference/threads#threads-list-tracking).

### `threads.get_delivery()`

Read whether the mail sent in a thread arrived

```python
def get_delivery(
    id: str,
    *,
    address: str | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadDeliveryResource
```

Returns what became of the mail this workspace sent in the thread, counted over every recipient of every message: how many bounced, reported it as spam, could not be sent to, or were held back by the suppression list, and how many messages reached only some of their recipients. It is the delivery warning the app shows on a thread.

A thread with no trouble answers zeroes beside the number of recipients, and a thread this workspace sent nothing in answers zero recipients. `emails.list_events` tells the story of one message. A key or an app limited to particular addresses counts only the messages sent from the addresses it covers.

Scopes: `emails:read`.

**Parameters**

- `id` (`str`, required): Thread id.
- `address` (`str`): Counts only the messages sent from this address. One the key does not reach counts nothing rather than failing.
- `api_key` (`str`): Reads with this key instead of the client's.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadDeliveryResource`, a dict with `object` set to `thread_delivery`, `threadId`, `recipients`, `bounced`, `complained`, `failed`, `suppressed`, `partialSends` and `reason`, an error one of the recipients came back with, or `None`.

**Example**

```python
from nextmail import nextmail

delivery = nextmail.threads.get_delivery('CAHk7pQ2x9LmZ4-mail.example.com')

if delivery['bounced'] + delivery['failed'] > 0:
    print(delivery['bounced'], 'bounced,', delivery['failed'], 'failed:', delivery['reason'])
```

**Notes**

- `recipients` counts to, cc and bcc together, once for each message each one was on.

Also available in: API [`GET /threads/{id}/delivery`](https://nextmail.sh/docs/api/reference/emails#get-threads-id-delivery); TypeScript [`threads.getDelivery()`](https://nextmail.sh/docs/sdk/reference/threads#getDelivery); Ruby [`threads.get_delivery`](https://nextmail.sh/docs/ruby/reference/threads#getDelivery); PHP [`threads->getDelivery`](https://nextmail.sh/docs/php/reference/threads#getDelivery); Go [`Threads.GetDelivery`](https://nextmail.sh/docs/go/reference/threads#getDelivery); Java [`threads().getDelivery`](https://nextmail.sh/docs/java/reference/threads#getDelivery); C# [`Threads.GetDeliveryAsync`](https://nextmail.sh/docs/csharp/reference/threads#getDelivery); CLI [`nextmail threads get-delivery`](https://nextmail.sh/docs/cli/reference/threads#threads-get-delivery).

### `threads.list_automations()`

Read which automations ran on a thread and what they did

```python
def list_automations(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[ThreadAutomationRunResource]
```

Returns every automation run that touched the thread, newest first: a run an email in it started, and a run that sent mail into it, such as an automatic reply, or sent the email a reply in it answers. Each one says which automation it was, what started it and the case the email matched (the address or domain that received it, the sender entry and the filters that held), the messages of the thread it started from or sent, and every step it ran with its outcome, oldest first. It is what the app shows on a conversation an automation handled.

An empty list means no automation acted on the thread. A run whose automation the key cannot read is left out: a member's key sees only the automations that member created. A key or an app limited to particular addresses reads only the threads it reaches.

Scopes: `threads:read`, `automations:read`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Reads with this key instead of the client's.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[ThreadAutomationRunResource]`, newest first, each a dict with `object` set to `thread_automation_run`, `id` (the enrollment), `automation` (`id`, `name` and `status`), `version`, `status`, `exitReason`, `source`, `startedAt`, `finishedAt`, `trigger`, `match` (the case the email matched, or `None`), `messages` (each with `id`, `role` set to `started` or `sent`, `stepKey` and `at`) and `steps` (each with `id`, `stepKey`, `kind`, `outcome`, `emailId`, `detail`, `at` and `step`, the step as the version defines it).

**Example**

```python
from nextmail import nextmail

runs = nextmail.threads.list_automations('thr_5c1e9a7b3d2f48e6a0b4c7d1')

for run in runs:
    matched = run['match']
    received_at = matched and (matched['address'] or matched['domain'])
    sent = [message for message in run['messages'] if message['role'] == 'sent']
    print(run['automation']['name'], run['status'], received_at, len(sent))
```

**Notes**

- Pass the `id` of a run to `automations.get_enrollment` with the automation id for the whole run with its contact.
- Runs started by email before this method existed show only through the mail they sent.

Also available in: API [`GET /threads/{id}/automations`](https://nextmail.sh/docs/api/reference/automations#get-threads-id-automations); TypeScript [`threads.listAutomations()`](https://nextmail.sh/docs/sdk/reference/threads#listAutomations); Ruby [`threads.list_automations`](https://nextmail.sh/docs/ruby/reference/threads#listAutomations); PHP [`threads->listAutomations`](https://nextmail.sh/docs/php/reference/threads#listAutomations); Go [`Threads.ListAutomations`](https://nextmail.sh/docs/go/reference/threads#listAutomations); Java [`threads().listAutomations`](https://nextmail.sh/docs/java/reference/threads#listAutomations); C# [`Threads.ListAutomationsAsync`](https://nextmail.sh/docs/csharp/reference/threads#listAutomations); CLI [`nextmail threads list-automations`](https://nextmail.sh/docs/cli/reference/threads#threads-list-automations).

### `threads.list_notes()`

List the notes on a thread

```python
def list_notes(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[ThreadNoteResource]
```

Returns every note on one thread, the Notes panel of the reading pane: pinned notes first, then the rest in the order they were arranged.

Notes are private to a person. A key reads and writes the notes of the workspace owner, and an app those of the person who connected it. A key limited to particular addresses reaches only the notes on threads that arrived at them.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[ThreadNoteResource]`, each with `id`, `threadId`, `content`, `color`, `pinned`, `order`, `createdAt` and `updatedAt`.

**Example**

```python
from nextmail import nextmail

notes = nextmail.threads.list_notes('thr_8f2c41d0a3b94e6f')

for note in notes:
    print('pinned' if note['pinned'] else '', note['content'])
```

**Notes**

- A thread delivered to no address the key covers is a 404.

Also available in: API [`GET /threads/{id}/notes`](https://nextmail.sh/docs/api/reference/notes#get-threads-id-notes); TypeScript [`threads.listNotes()`](https://nextmail.sh/docs/sdk/reference/threads#listNotes); Ruby [`threads.list_notes`](https://nextmail.sh/docs/ruby/reference/threads#listNotes); PHP [`threads->listNotes`](https://nextmail.sh/docs/php/reference/threads#listNotes); Go [`Threads.ListNotes`](https://nextmail.sh/docs/go/reference/threads#listNotes); Java [`threads().listNotes`](https://nextmail.sh/docs/java/reference/threads#listNotes); C# [`Threads.ListNotesAsync`](https://nextmail.sh/docs/csharp/reference/threads#listNotes); CLI [`nextmail threads list-notes`](https://nextmail.sh/docs/cli/reference/threads#threads-list-notes).

### `threads.create_note()`

Add a note to a thread

```python
def create_note(
    id: str,
    body: ThreadNoteCreate,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadNoteResource
```

Pins a private note to a thread, as the Notes panel does. A new note goes after the others, and `pinned` keeps it at the top.

Notes are private to a person. A key reads and writes the notes of the workspace owner, and an app those of the person who connected it. A key limited to particular addresses reaches only the notes on threads that arrived at them.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `body['content']` (`str`, required): The text of the note, up to 20,000 characters. Leading and trailing spaces are trimmed.
- `body['color']` (`ThreadNoteColor`): One of the eight the app offers: `default`, `red`, `orange`, `yellow`, `green`, `blue`, `purple` or `pink`. Defaults to `default`.
- `body['pinned']` (`bool`): Keeps the note above the others. Defaults to `False`.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadNoteResource` for the new note.

**Example**

```python
from nextmail import nextmail

note = nextmail.threads.create_note(
    'thr_8f2c41d0a3b94e6f',
    {
        'content': 'Waiting on the signed contract before replying.',
        'color': 'yellow',
        'pinned': True,
    },
)

print(note['id'], note['order'])
```

**Notes**

- The SDK does not retry it, because a second call would add a second note.

Also available in: API [`POST /threads/{id}/notes`](https://nextmail.sh/docs/api/reference/notes#post-threads-id-notes); TypeScript [`threads.createNote()`](https://nextmail.sh/docs/sdk/reference/threads#createNote); Ruby [`threads.create_note`](https://nextmail.sh/docs/ruby/reference/threads#createNote); PHP [`threads->createNote`](https://nextmail.sh/docs/php/reference/threads#createNote); Go [`Threads.CreateNote`](https://nextmail.sh/docs/go/reference/threads#createNote); Java [`threads().createNote`](https://nextmail.sh/docs/java/reference/threads#createNote); C# [`Threads.CreateNoteAsync`](https://nextmail.sh/docs/csharp/reference/threads#createNote); CLI [`nextmail threads create-note`](https://nextmail.sh/docs/cli/reference/threads#threads-create-note).

### `threads.update_note()`

Change a note

```python
def update_note(
    id: str,
    note_id: str,
    patch: ThreadNoteUpdate,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadNoteResource
```

Changes the text of a note, its colour or whether it is pinned. Give at least one of the three. A note id that is not on this thread is a 404, even when the note exists on another thread.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `note_id` (`str`, required): The note's id, from `list_notes`.
- `patch['content']` (`str`): The new text, up to 20,000 characters.
- `patch['color']` (`ThreadNoteColor`): The new colour.
- `patch['pinned']` (`bool`): Pins or unpins it.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadNoteResource` as it is now.

**Example**

```python
from nextmail import nextmail

note = nextmail.threads.update_note(
    'thr_8f2c41d0a3b94e6f', 'b3d1f0c2-7a4e-4f7b-9c1d-2e8f6a5b4c3d', {'pinned': False}
)

print(note['pinned'], note['updatedAt'])
```

**Notes**

- Safe to repeat: setting the same values twice leaves the note as it was.

Also available in: API [`PATCH /threads/{id}/notes/{noteId}`](https://nextmail.sh/docs/api/reference/notes#patch-threads-id-notes-noteid); TypeScript [`threads.updateNote()`](https://nextmail.sh/docs/sdk/reference/threads#updateNote); Ruby [`threads.update_note`](https://nextmail.sh/docs/ruby/reference/threads#updateNote); PHP [`threads->updateNote`](https://nextmail.sh/docs/php/reference/threads#updateNote); Go [`Threads.UpdateNote`](https://nextmail.sh/docs/go/reference/threads#updateNote); Java [`threads().updateNote`](https://nextmail.sh/docs/java/reference/threads#updateNote); C# [`Threads.UpdateNoteAsync`](https://nextmail.sh/docs/csharp/reference/threads#updateNote); CLI [`nextmail threads update-note`](https://nextmail.sh/docs/cli/reference/threads#threads-update-note).

### `threads.delete_note()`

Delete a note

```python
def delete_note(
    id: str,
    note_id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> DeletedThreadNoteResource
```

Deletes a note for good. There is no bin for notes.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `note_id` (`str`, required): The note's id, from `list_notes`.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`DeletedThreadNoteResource` with `object` set to `note`, the `id` and `threadId`, and `deleted` set to `True`.

**Example**

```python
from nextmail import nextmail

deleted = nextmail.threads.delete_note(
    'thr_8f2c41d0a3b94e6f', 'b3d1f0c2-7a4e-4f7b-9c1d-2e8f6a5b4c3d'
)

print(deleted['id'], deleted['deleted'])
```

**Notes**

- The SDK does not retry a delete. A 404 on your own second attempt after a lost response means the first one worked.

Also available in: API [`DELETE /threads/{id}/notes/{noteId}`](https://nextmail.sh/docs/api/reference/notes#delete-threads-id-notes-noteid); TypeScript [`threads.deleteNote()`](https://nextmail.sh/docs/sdk/reference/threads#deleteNote); Ruby [`threads.delete_note`](https://nextmail.sh/docs/ruby/reference/threads#deleteNote); PHP [`threads->deleteNote`](https://nextmail.sh/docs/php/reference/threads#deleteNote); Go [`Threads.DeleteNote`](https://nextmail.sh/docs/go/reference/threads#deleteNote); Java [`threads().deleteNote`](https://nextmail.sh/docs/java/reference/threads#deleteNote); C# [`Threads.DeleteNoteAsync`](https://nextmail.sh/docs/csharp/reference/threads#deleteNote); CLI [`nextmail threads delete-note`](https://nextmail.sh/docs/cli/reference/threads#threads-delete-note).

### `threads.reorder_notes()`

Arrange the notes on a thread

```python
def reorder_notes(
    id: str,
    ids: Sequence[str],
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[ThreadNoteResource]
```

Sets the order of every note on a thread at once, first to last, as dragging them in the Notes panel does. Pinned notes still come first.

`ids` has to name every note on the thread exactly once. Anything else is a 422 `invalid_parameter` on `ids`, and nothing moves.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `ids` (`Sequence[str]`, required): Every note id on the thread, in the order you want them, as a list or tuple.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[ThreadNoteResource]` in the new order.

**Example**

```python
from nextmail import nextmail

notes = nextmail.threads.list_notes('thr_8f2c41d0a3b94e6f')
newest_first = [note['id'] for note in reversed(notes)]

reordered = nextmail.threads.reorder_notes('thr_8f2c41d0a3b94e6f', newest_first)
print([note['content'] for note in reordered])
```

**Notes**

- Safe to repeat: the same order twice leaves the notes as they were.

Also available in: API [`POST /threads/{id}/notes/reorder`](https://nextmail.sh/docs/api/reference/notes#post-threads-id-notes-reorder); TypeScript [`threads.reorderNotes()`](https://nextmail.sh/docs/sdk/reference/threads#reorderNotes); Ruby [`threads.reorder_notes`](https://nextmail.sh/docs/ruby/reference/threads#reorderNotes); PHP [`threads->reorderNotes`](https://nextmail.sh/docs/php/reference/threads#reorderNotes); Go [`Threads.ReorderNotes`](https://nextmail.sh/docs/go/reference/threads#reorderNotes); Java [`threads().reorderNotes`](https://nextmail.sh/docs/java/reference/threads#reorderNotes); C# [`Threads.ReorderNotesAsync`](https://nextmail.sh/docs/csharp/reference/threads#reorderNotes); CLI [`nextmail threads reorder-notes`](https://nextmail.sh/docs/cli/reference/threads#threads-reorder-notes).

### `threads.counts()`

Count the mail in each folder

```python
def counts(
    *,
    address: str | None = None,
    hide_labelled: bool | None = None,
    api_key: str | None = None,
    timeout: float | None = None,
) -> MailboxCountsResource
```

Returns what the sidebar of the app shows: how many conversations each folder holds and how many of them are unread, how many drafts are waiting, how many conversations each of your labels has in each folder, how many inbox conversations sit in each inbox tab, and how many inbox conversations arrived at each address of the workspace.

`folders` has one row per folder, named by its label id in lower case: `inbox`, `sent`, `spam`, `archive`, `trash` and `snoozed`, then `draft`, whose `count` is the drafts waiting to be sent and whose `unread` is always 0, then `unread`, whose `count` is the unread conversations in the inbox. `labels` has one row for each of your labels and each folder it has conversations in, with `id`, `folder`, `count` and `unread`, so a label with nothing in a folder has no row for it. `categories` has one row for each inbox tab, with `category`, `count` and `unread`, counting inbox conversations only: `primary`, `promotions`, `updates`, `social` and `forums`, where `primary` is everything not sorted into another tab. `unlabelled` counts the inbox conversations that carry none of your labels, with `count`, `unread` and the same count for each tab under `categories`, which is what the inbox of the app lists unless Labelled mail is ticked in its Filters menu. `addresses` counts the inbox per address the mail was delivered to, with `None` for mail that recorded none. `team` counts the team views of a shared inbox for the person the key or app acts for: `assigned` the open conversations assigned to them, `unassigned` the open conversations nobody has, each with `count` and `unread`, and `mentions` the conversations outside Spam and the bin where a team comment mentions them, with `count`, `unread` and `unseen`, the conversations with a mention newer than the last time they opened its comments in the app. A conversation is open while it is in the inbox, and `assigned` and `unassigned` leave out the conversations that carry one of your labels, as the inbox does, unless that person shows Labelled mail in the inbox.

A key limited to particular addresses counts only the mail that arrived at them and the drafts written from them. `address` narrows every count to one address, and one the key does not reach counts nothing rather than failing.

Scopes: `threads:read`.

**Parameters**

- `address` (`str`): Count only the mail delivered to this address.
- `hide_labelled` (`bool`): `True` leaves labelled mail out of the `team` counts and `False` counts it. Left out, the counts follow whether the person shows labelled mail in the inbox, as the app does.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`MailboxCountsResource` with `object` set to `mailbox_counts`, `folders`, each with `label`, `count` and `unread`, `addresses`, each with `address` and `count`, `labels`, each with `id`, `folder`, `count` and `unread`, and `categories`, each with `category`, `count` and `unread`. `unlabelled` holds `count`, `unread` and `categories` for the inbox conversations with no label. `team` holds `assigned`, `unassigned` and `mentions`, each with `count` and `unread`, and `mentions` also has `unseen`.

**Example**

```python
from nextmail import nextmail

counts = nextmail.threads.counts()
inbox = next((row for row in counts['folders'] if row['label'] == 'inbox'), None)

if inbox is not None:
    print(inbox['unread'], 'unread of', inbox['count'])

for row in counts['addresses']:
    print(row['address'] or '(none)', row['count'])

for tab in counts['categories']:
    print(tab['category'], tab['count'], tab['unread'])

print(counts['team']['unassigned']['count'], 'open and nobody has them')
```

**Notes**

- Read only, so the SDK retries it after a network failure like any other read.

Also available in: API [`GET /threads/counts`](https://nextmail.sh/docs/api/reference/threads#get-threads-counts); TypeScript [`threads.counts()`](https://nextmail.sh/docs/sdk/reference/threads#counts); Ruby [`threads.counts`](https://nextmail.sh/docs/ruby/reference/threads#counts); PHP [`threads->counts`](https://nextmail.sh/docs/php/reference/threads#counts); Go [`Threads.Counts`](https://nextmail.sh/docs/go/reference/threads#counts); Java [`threads().counts`](https://nextmail.sh/docs/java/reference/threads#counts); C# [`Threads.CountsAsync`](https://nextmail.sh/docs/csharp/reference/threads#counts); CLI [`nextmail threads counts`](https://nextmail.sh/docs/cli/reference/threads#threads-counts).

### `threads.summary()`

Read the summary of a thread

```python
def summary(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadAiSummaryResource
```

Returns the short AI summary the reading pane shows above a thread. A summary is written the first time it is asked for and then kept, and the first request after a newer message arrives writes it again, so reading one is cheap.

`state` is `ready` with the text in `summary`, `pending` while the first one is being written, `failed` when the last try did not work, or `none` when there is nothing to summarise, such as a thread holding a message that arrived encrypted, whose body Nextmail never reads. While a newer summary is being written, the one before it comes back as `ready`. A `pending` answer starts the writing, so ask again a few seconds later, and after a `failed` one asking again tries once more.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadAiSummaryResource` with `object` set to `thread_summary`, `threadId`, `state` and `summary`, which is `None` unless `state` is `ready`.

**Example**

```python
import time

from nextmail import nextmail

result = nextmail.threads.summary('thr_8f2c41d0a3b94e6f')

if result['state'] == 'pending':
    time.sleep(5)
    result = nextmail.threads.summary('thr_8f2c41d0a3b94e6f')

print(result['summary'] or result['state'])
```

**Notes**

- Summaries spend no AI actions, whether one is written or only read.
- A thread delivered to no address the key covers is a 404.

Also available in: API [`GET /threads/{id}/summary`](https://nextmail.sh/docs/api/reference/threads#get-threads-id-summary); TypeScript [`threads.summary()`](https://nextmail.sh/docs/sdk/reference/threads#summary); Ruby [`threads.summary`](https://nextmail.sh/docs/ruby/reference/threads#summary); PHP [`threads->summary`](https://nextmail.sh/docs/php/reference/threads#summary); Go [`Threads.Summary`](https://nextmail.sh/docs/go/reference/threads#summary); Java [`threads().summary`](https://nextmail.sh/docs/java/reference/threads#summary); C# [`Threads.SummaryAsync`](https://nextmail.sh/docs/csharp/reference/threads#summary); CLI [`nextmail threads summary`](https://nextmail.sh/docs/cli/reference/threads#threads-summary).

### `threads.reply_suggestions()`

Suggest replies to a thread

```python
def reply_suggestions(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ReplySuggestionsResource
```

Returns up to three short replies to the latest message of the thread, the ones the reading pane offers under it. Each has a `label`, a few words that say what it answers, and a `body`, the reply itself in plain text, ready to send with `emails.send` or to keep with `drafts.create`. They are written in the language of that message and the voice of the mail this workspace sends, from the conversation, what was written to this correspondent before, what is known about their organisation and, when the message asks for a time, the busy times of the calendar.

Suggestions are written once for each new message and kept, so asking again is free until another message arrives. `state` is `ready` with the suggestions, `pending` while they are being written, so ask again a few seconds later, or `none` when the message needs no reply: your own reply came last, or it is a newsletter, an automated notice, mail from a no-reply address, spam or an encrypted message. Every thread is `none` in a workspace that turned `replySuggestions` off with `settings.update`.

`sources` names the knowledge base items the suggestions drew on: the pinned notes at the levels of the receiving address and the items whose passages matched the message, each with `id`, `title`, `kind`, `scope` and `url`. It is empty when none were used.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ReplySuggestionsResource` with `object` set to `reply_suggestions`, `threadId`, `messageId`, `state`, `suggestions`, each with `label` and `body`, and `sources`. `messageId` names the message they answer, `suggestions` is empty unless `state` is `ready`, and `sources` lists the knowledge base items they drew on.

**Example**

```python
import time

from nextmail import nextmail

result = nextmail.threads.reply_suggestions('thr_8f2c41d0a3b94e6f')

if result['state'] == 'pending':
    time.sleep(5)
    result = nextmail.threads.reply_suggestions('thr_8f2c41d0a3b94e6f')

for suggestion in result['suggestions']:
    print(f'{suggestion["label"]}: {suggestion["body"]}')
```

**Notes**

- Writing suggestions spends none of the workspace's AI actions. A workspace has suggestions written for a limited number of new messages a day, and past it a thread reads `none` until the next day.
- A thread delivered to no address the key covers is a 404.
- A server with no AI configured answers 409 `ai_not_configured`.

Also available in: API [`GET /threads/{id}/reply-suggestions`](https://nextmail.sh/docs/api/reference/threads#get-threads-id-reply-suggestions); TypeScript [`threads.replySuggestions()`](https://nextmail.sh/docs/sdk/reference/threads#replySuggestions); Ruby [`threads.reply_suggestions`](https://nextmail.sh/docs/ruby/reference/threads#replySuggestions); PHP [`threads->replySuggestions`](https://nextmail.sh/docs/php/reference/threads#replySuggestions); Go [`Threads.ReplySuggestions`](https://nextmail.sh/docs/go/reference/threads#replySuggestions); Java [`threads().replySuggestions`](https://nextmail.sh/docs/java/reference/threads#replySuggestions); C# [`Threads.ReplySuggestionsAsync`](https://nextmail.sh/docs/csharp/reference/threads#replySuggestions); CLI [`nextmail threads reply-suggestions`](https://nextmail.sh/docs/cli/reference/threads#threads-reply-suggestions).

### `threads.restore()`

Take a thread out of the Bin

```python
def restore(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> RestoredThreadResource
```

Puts a thread back in the inbox, out of the Bin and out of Spam, which is what Restore from Bin and Move to inbox do in the app. It is the undo of `trash`.

Calling it on a thread that is already in the inbox changes nothing and returns the same body, which is why the SDK retries it.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`RestoredThreadResource` with `object` set to `thread`, the `id`, and `restored` set to `True`.

**Example**

```python
from nextmail import nextmail

nextmail.threads.trash('thr_8f2c41d0a3b94e6f')

restored = nextmail.threads.restore('thr_8f2c41d0a3b94e6f')
print(restored['id'], restored['restored'])
```

**Notes**

- A thread that was archived before it went to the Bin comes back to the inbox, not to the archive.
- A thread delivered to no address the key covers is a 404.

Also available in: API [`POST /threads/{id}/restore`](https://nextmail.sh/docs/api/reference/threads#post-threads-id-restore); TypeScript [`threads.restore()`](https://nextmail.sh/docs/sdk/reference/threads#restore); Ruby [`threads.restore`](https://nextmail.sh/docs/ruby/reference/threads#restore); PHP [`threads->restore`](https://nextmail.sh/docs/php/reference/threads#restore); Go [`Threads.Restore`](https://nextmail.sh/docs/go/reference/threads#restore); Java [`threads().restore`](https://nextmail.sh/docs/java/reference/threads#restore); C# [`Threads.RestoreAsync`](https://nextmail.sh/docs/csharp/reference/threads#restore); CLI [`nextmail threads restore`](https://nextmail.sh/docs/cli/reference/threads#threads-restore).

### `threads.delete()`

Delete a thread for good

```python
def delete(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> DeletedThreadResource
```

Deletes every message in a thread, with its attachments, which is what Delete from Bin does in the app. It cannot be undone.

It works on a thread in any folder, so call `trash` instead when you only mean to put the thread out of the way: a trashed thread stays readable and `restore` brings it back.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`DeletedThreadResource` with `object` set to `thread`, the `id`, and `deleted` set to `True`.

**Example**

```python
from nextmail import NextmailApiError, nextmail

try:
    deleted = nextmail.threads.delete('thr_8f2c41d0a3b94e6f')
except NextmailApiError as error:
    if not error.is_not_found:
        raise
    print('Already gone, or the key does not reach it')
else:
    print(deleted['id'], deleted['deleted'])
```

**Notes**

- The SDK does not retry a delete. A 404 on your own second attempt after a lost response means the first one worked.
- A 500 `thread_delete_failed` means nothing was removed, so the call is safe to repeat.
- A thread delivered to no address the key covers is a 404.

Also available in: API [`DELETE /threads/{id}`](https://nextmail.sh/docs/api/reference/threads#delete-threads-id); TypeScript [`threads.delete()`](https://nextmail.sh/docs/sdk/reference/threads#delete); Ruby [`threads.delete`](https://nextmail.sh/docs/ruby/reference/threads#delete); PHP [`threads->delete`](https://nextmail.sh/docs/php/reference/threads#delete); Go [`Threads.Delete`](https://nextmail.sh/docs/go/reference/threads#delete); Java [`threads().delete`](https://nextmail.sh/docs/java/reference/threads#delete); C# [`Threads.DeleteAsync`](https://nextmail.sh/docs/csharp/reference/threads#delete); CLI [`nextmail threads delete`](https://nextmail.sh/docs/cli/reference/threads#threads-delete).

### `threads.unsubscribe()`

Unsubscribe from the sender of a thread

```python
def unsubscribe(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> UnsubscribeResultResource
```

Does what the Unsubscribe button of the reading pane does: finds the subscription behind the newest message of the thread that carries a `List-Unsubscribe` header and unsubscribes from it the way the sender asks for, with a one-click request or an unsubscribe email. A sender that only offers a page cannot be unsubscribed by a program, so `method` is `link` and `url` is the page a person has to open.

A thread with no unsubscribe header is a 422 `unsubscribe_unsupported`, and a thread delivered to no address the key covers is a 404.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`UnsubscribeResultResource` with `object` set to `unsubscribe`, `threadId`, `subscriptionId`, `method`, `url` and `binned`.

**Example**

```python
from nextmail import nextmail

result = nextmail.threads.unsubscribe('thr_8f2c41d0a3b94e6f')

if result['method'] == 'link':
    print('Open this page to finish:', result['url'])
else:
    print('Unsubscribed by', result['method'])
```

**Notes**

- The SDK does not retry it, because a second call can send a second unsubscribe email.

Also available in: API [`POST /threads/{id}/unsubscribe`](https://nextmail.sh/docs/api/reference/subscriptions#post-threads-id-unsubscribe); TypeScript [`threads.unsubscribe()`](https://nextmail.sh/docs/sdk/reference/threads#unsubscribe); Ruby [`threads.unsubscribe`](https://nextmail.sh/docs/ruby/reference/threads#unsubscribe); PHP [`threads->unsubscribe`](https://nextmail.sh/docs/php/reference/threads#unsubscribe); Go [`Threads.Unsubscribe`](https://nextmail.sh/docs/go/reference/threads#unsubscribe); Java [`threads().unsubscribe`](https://nextmail.sh/docs/java/reference/threads#unsubscribe); C# [`Threads.UnsubscribeAsync`](https://nextmail.sh/docs/csharp/reference/threads#unsubscribe); CLI [`nextmail threads unsubscribe`](https://nextmail.sh/docs/cli/reference/threads#threads-unsubscribe).

### `threads.get_event()`

Read the event a thread carries

```python
def get_event(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> CalendarEventResource
```

Returns the calendar event that came with an invitation in the thread, as the invitation card of the reading pane shows it. Answer it with `calendar.respond_to_event`.

Scopes: `calendar:read`.

**Parameters**

- `id` (`str`, required): Thread id, as `threads.list` returns it.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`CalendarEventResource`, as `calendar.get_event` returns it.

**Example**

```python
from nextmail import nextmail

event = nextmail.threads.get_event('thr_8f2c41d0a3b94e6f')

print(event['summary'], event['start'], event['location'])
```

**Notes**

- A thread with no event, or one the key does not reach, is a 404.

Also available in: API [`GET /threads/{id}/event`](https://nextmail.sh/docs/api/reference/calendar#get-threads-id-event); TypeScript [`threads.getEvent()`](https://nextmail.sh/docs/sdk/reference/threads#getEvent); Ruby [`threads.get_event`](https://nextmail.sh/docs/ruby/reference/threads#getEvent); PHP [`threads->getEvent`](https://nextmail.sh/docs/php/reference/threads#getEvent); Go [`Threads.GetEvent`](https://nextmail.sh/docs/go/reference/threads#getEvent); Java [`threads().getEvent`](https://nextmail.sh/docs/java/reference/threads#getEvent); C# [`Threads.GetEventAsync`](https://nextmail.sh/docs/csharp/reference/threads#getEvent); CLI [`nextmail threads get-event`](https://nextmail.sh/docs/cli/reference/threads#threads-get-event).

### `threads.list_sender_categories()`

List the senders that always go to one inbox tab

```python
def list_sender_categories(
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[SenderCategoryResource]
```

Returns the senders whose mail always goes to one inbox tab, by address. New mail is sorted into Primary, Promotions, Updates, Social or Forums by plain rules, and a choice saved here wins over them. `list` takes `category=` to read one tab.

The choices belong to the workspace and apply to every address in it. A workspace holds at most 2,000 of them, and they come back as one plain list with no paging.

Scopes: `threads:read`.

**Parameters**

- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[SenderCategoryResource]`, each with `object` set to `sender_category`, `sender`, `category` and `updatedAt`, with `sender` in lower case and `category` the tab their mail goes to.

**Example**

```python
from nextmail import nextmail

choices = nextmail.threads.list_sender_categories()

for choice in choices:
    print(choice['sender'], choice['category'])
```

**Notes**

- A key or an app limited to particular addresses or domains can read the choices but not change them.
- Read only, so the SDK retries it after a network failure like any other read.

Also available in: API [`GET /sender-categories`](https://nextmail.sh/docs/api/reference/threads#get-sender-categories); TypeScript [`threads.listSenderCategories()`](https://nextmail.sh/docs/sdk/reference/threads#listSenderCategories); Ruby [`threads.list_sender_categories`](https://nextmail.sh/docs/ruby/reference/threads#listSenderCategories); PHP [`threads->listSenderCategories`](https://nextmail.sh/docs/php/reference/threads#listSenderCategories); Go [`Threads.ListSenderCategories`](https://nextmail.sh/docs/go/reference/threads#listSenderCategories); Java [`threads().listSenderCategories`](https://nextmail.sh/docs/java/reference/threads#listSenderCategories); C# [`Threads.ListSenderCategoriesAsync`](https://nextmail.sh/docs/csharp/reference/threads#listSenderCategories); CLI [`nextmail threads list-sender-categories`](https://nextmail.sh/docs/cli/reference/threads#threads-list-sender-categories).

### `threads.set_sender_category()`

Always sort a sender into one inbox tab

```python
def set_sender_category(
    email: str,
    category: InboxCategory,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> SenderCategoryResource
```

Saves the tab for one sender and moves the inbox threads whose newest message is from them, up to the newest 1,000, into it. Mail from them is sorted there from now on, whatever the rules would say. Saving again replaces the choice.

A workspace holds at most 2,000 choices, and the call past that is a 422 `sender_category_limit_reached`. They apply to every address in the workspace, so a key or an app limited to particular addresses or domains can read them but not change them, and gets a 422 `capability_unsupported`.

Scopes: `threads:write`.

**Parameters**

- `email` (`str`, required): The address of the sender, compared without case.
- `category` (`InboxCategory`, required): The inbox tab their mail goes to: `primary`, `promotions`, `updates`, `social` or `forums`, one of `INBOX_CATEGORIES`.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`SenderCategoryResource` with `object` set to `sender_category`, `sender` in lower case, `category` and `updatedAt`.

**Example**

```python
from nextmail import nextmail

choice = nextmail.threads.set_sender_category('news@example.com', 'promotions')

print(choice['sender'], choice['category'], choice['updatedAt'])
```

**Notes**

- An address or a category that is not valid is a 422 `invalid_parameter`.
- Choosing `primary` keeps a sender out of the other tabs, which is how to stop a newsletter you read from being sorted away.
- The SDK retries this call after a network failure, which is safe because saving the same choice twice leaves the same choice.
- The choices apply to every address in the workspace, so a key or an app limited to particular addresses or domains can read them but not change them, and gets a 422 `capability_unsupported`, and an app acting for a member whose role does not reach every address is refused with 403 `owner_only`.

Also available in: API [`PUT /sender-categories/{email}`](https://nextmail.sh/docs/api/reference/threads#put-sender-categories-email); TypeScript [`threads.setSenderCategory()`](https://nextmail.sh/docs/sdk/reference/threads#setSenderCategory); Ruby [`threads.set_sender_category`](https://nextmail.sh/docs/ruby/reference/threads#setSenderCategory); PHP [`threads->setSenderCategory`](https://nextmail.sh/docs/php/reference/threads#setSenderCategory); Go [`Threads.SetSenderCategory`](https://nextmail.sh/docs/go/reference/threads#setSenderCategory); Java [`threads().setSenderCategory`](https://nextmail.sh/docs/java/reference/threads#setSenderCategory); C# [`Threads.SetSenderCategoryAsync`](https://nextmail.sh/docs/csharp/reference/threads#setSenderCategory); CLI [`nextmail threads set-sender-category`](https://nextmail.sh/docs/cli/reference/threads#threads-set-sender-category).

### `threads.clear_sender_category()`

Remove the tab chosen for a sender

```python
def clear_sender_category(
    email: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> DeletedSenderCategoryResource
```

Removes the choice, so new mail from the sender is sorted by the rules again. Threads already sorted stay where they are.

Scopes: `threads:write`.

**Parameters**

- `email` (`str`, required): The address of the sender, compared without case.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`DeletedSenderCategoryResource` with `object` set to `sender_category`, `sender` in lower case, and `deleted` set to `True`.

**Example**

```python
from nextmail import nextmail

removed = nextmail.threads.clear_sender_category('news@example.com')

print(removed['sender'], removed['deleted'])
```

**Notes**

- A sender with no saved choice is a 404. The SDK does not retry a delete, so a 404 on your own second attempt after a lost response means the first one worked.
- The choices apply to every address in the workspace, so a key or an app limited to particular addresses or domains cannot change them and gets a 422 `capability_unsupported`, and an app acting for a member whose role does not reach every address is refused with 403 `owner_only`.

Also available in: API [`DELETE /sender-categories/{email}`](https://nextmail.sh/docs/api/reference/threads#delete-sender-categories-email); TypeScript [`threads.clearSenderCategory()`](https://nextmail.sh/docs/sdk/reference/threads#clearSenderCategory); Ruby [`threads.clear_sender_category`](https://nextmail.sh/docs/ruby/reference/threads#clearSenderCategory); PHP [`threads->clearSenderCategory`](https://nextmail.sh/docs/php/reference/threads#clearSenderCategory); Go [`Threads.ClearSenderCategory`](https://nextmail.sh/docs/go/reference/threads#clearSenderCategory); Java [`threads().clearSenderCategory`](https://nextmail.sh/docs/java/reference/threads#clearSenderCategory); C# [`Threads.ClearSenderCategoryAsync`](https://nextmail.sh/docs/csharp/reference/threads#clearSenderCategory); CLI [`nextmail threads clear-sender-category`](https://nextmail.sh/docs/cli/reference/threads#threads-clear-sender-category).

### `threads.get_team()`

Read who has a thread

```python
def get_team(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadTeamResource
```

Returns the thread as the team sees it: who it is assigned to, who marked it done, how many comments it has, who else is writing a reply in the app right now, and everyone who can see it.

Only people who can see a thread can be given it or mentioned on it: the workspace owner, members who reach every address, and members who hold its address or its domain. A key acts for the workspace owner.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadTeamResource` with `object` set to `thread_team`, `threadId`, `assignment`, `commentCount`, `replying` and `team`, where each person has `id`, `name` and `email`.

**Example**

```python
from nextmail import nextmail

team = nextmail.threads.get_team('thr_8f2c41d0a3b94e6f')
assignee = team['assignment']['assignee']

print(assignee['email'] if assignee else 'nobody', len(team['team']))
```

**Notes**

- A thread delivered to no address the key covers is a 404.

Also available in: API [`GET /threads/{id}/team`](https://nextmail.sh/docs/api/reference/team-inbox#get-threads-id-team); TypeScript [`threads.getTeam()`](https://nextmail.sh/docs/sdk/reference/threads#getTeam); Ruby [`threads.get_team`](https://nextmail.sh/docs/ruby/reference/threads#getTeam); PHP [`threads->getTeam`](https://nextmail.sh/docs/php/reference/threads#getTeam); Go [`Threads.GetTeam`](https://nextmail.sh/docs/go/reference/threads#getTeam); Java [`threads().getTeam`](https://nextmail.sh/docs/java/reference/threads#getTeam); C# [`Threads.GetTeamAsync`](https://nextmail.sh/docs/csharp/reference/threads#getTeam); CLI [`nextmail threads get-team`](https://nextmail.sh/docs/cli/reference/threads#threads-get-team).

### `threads.assign()`

Assign a thread

```python
def assign(
    id: str,
    assignee_id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadAssignmentResource
```

Gives the thread to one person, who is emailed unless they assigned it to themselves.

Only people who can see a thread can be given it or mentioned on it: the workspace owner, members who reach every address, and members who hold its address or its domain. A key acts for the workspace owner.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `assignee_id` (`str`, required): The user id of the person to give it to, as `get_team` lists them in `team`.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadAssignmentResource` with `object` set to `thread_assignment`, `threadId`, `assignee`, `assignedBy`, `assignedAt`, `doneBy` and `doneAt`: who has the thread now.

**Example**

```python
from nextmail import nextmail

assignment = nextmail.threads.assign('thr_8f2c41d0a3b94e6f', 'usr_2f9c1d')
assignee = assignment['assignee']

print(assignee['email'] if assignee else 'nobody')
```

**Notes**

- Somebody who cannot see the thread is a 422 `invalid_parameter` on `assigneeId`.

Also available in: API [`PUT /threads/{id}/assignee`](https://nextmail.sh/docs/api/reference/team-inbox#put-threads-id-assignee); TypeScript [`threads.assign()`](https://nextmail.sh/docs/sdk/reference/threads#assign); Ruby [`threads.assign`](https://nextmail.sh/docs/ruby/reference/threads#assign); PHP [`threads->assign`](https://nextmail.sh/docs/php/reference/threads#assign); Go [`Threads.Assign`](https://nextmail.sh/docs/go/reference/threads#assign); Java [`threads().assign`](https://nextmail.sh/docs/java/reference/threads#assign); C# [`Threads.AssignAsync`](https://nextmail.sh/docs/csharp/reference/threads#assign); CLI [`nextmail threads assign`](https://nextmail.sh/docs/cli/reference/threads#threads-assign).

### `threads.unassign()`

Unassign a thread

```python
def unassign(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadAssignmentResource
```

Leaves the thread with nobody.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadAssignmentResource` with `assignee` set to `None`.

**Example**

```python
from nextmail import nextmail

assignment = nextmail.threads.unassign('thr_8f2c41d0a3b94e6f')

print(assignment['assignee'])
```

Also available in: API [`DELETE /threads/{id}/assignee`](https://nextmail.sh/docs/api/reference/team-inbox#delete-threads-id-assignee); TypeScript [`threads.unassign()`](https://nextmail.sh/docs/sdk/reference/threads#unassign); Ruby [`threads.unassign`](https://nextmail.sh/docs/ruby/reference/threads#unassign); PHP [`threads->unassign`](https://nextmail.sh/docs/php/reference/threads#unassign); Go [`Threads.Unassign`](https://nextmail.sh/docs/go/reference/threads#unassign); Java [`threads().unassign`](https://nextmail.sh/docs/java/reference/threads#unassign); C# [`Threads.UnassignAsync`](https://nextmail.sh/docs/csharp/reference/threads#unassign); CLI [`nextmail threads unassign`](https://nextmail.sh/docs/cli/reference/threads#threads-unassign).

### `threads.set_replying()`

Show you are replying to a thread

```python
def set_replying(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadReplyingResource
```

Tells everyone else who can see the thread that the person the key or app acts for is writing a reply, as the app does while someone types one, so nobody answers twice. It shows in `replying` of `get_team` for 30 seconds, until `expiresAt`, so call it again while the reply is still being written, and `clear_replying` takes it away at once. An API key shows the workspace owner.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadReplyingResource`, a dict with `object` set to `thread_replying`, `threadId`, `replying` set to `True` and `expiresAt`, when it stops showing unless you call again.

**Example**

```python
from nextmail import nextmail

mark = nextmail.threads.set_replying('CAHk7pQ2x9LmZ4-mail.example.com')

print('The others see you replying until', mark['expiresAt'])
```

**Notes**

- A thread delivered to no address the key covers is a 404.
- Retried automatically on network failure, since showing the mark again only moves `expiresAt`.

Also available in: API [`PUT /threads/{id}/replying`](https://nextmail.sh/docs/api/reference/team-inbox#put-threads-id-replying); TypeScript [`threads.setReplying()`](https://nextmail.sh/docs/sdk/reference/threads#setReplying); Ruby [`threads.set_replying`](https://nextmail.sh/docs/ruby/reference/threads#setReplying); PHP [`threads->setReplying`](https://nextmail.sh/docs/php/reference/threads#setReplying); Go [`Threads.SetReplying`](https://nextmail.sh/docs/go/reference/threads#setReplying); Java [`threads().setReplying`](https://nextmail.sh/docs/java/reference/threads#setReplying); C# [`Threads.SetReplyingAsync`](https://nextmail.sh/docs/csharp/reference/threads#setReplying); CLI [`nextmail threads set-replying`](https://nextmail.sh/docs/cli/reference/threads#threads-set-replying).

### `threads.clear_replying()`

Stop showing you are replying

```python
def clear_replying(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadReplyingResource
```

Takes away at once the mark `set_replying` put on the thread, after the reply was sent or given up. Taking it away when it is not there changes nothing.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadReplyingResource` with `replying` set to `False` and `expiresAt` set to `None`.

**Example**

```python
from nextmail import nextmail

mark = nextmail.threads.clear_replying('CAHk7pQ2x9LmZ4-mail.example.com')

print(mark['replying'])
```

**Notes**

- A thread delivered to no address the key covers is a 404.
- Retried automatically on network failure, since taking the mark away twice changes nothing.

Also available in: API [`DELETE /threads/{id}/replying`](https://nextmail.sh/docs/api/reference/team-inbox#delete-threads-id-replying); TypeScript [`threads.clearReplying()`](https://nextmail.sh/docs/sdk/reference/threads#clearReplying); Ruby [`threads.clear_replying`](https://nextmail.sh/docs/ruby/reference/threads#clearReplying); PHP [`threads->clearReplying`](https://nextmail.sh/docs/php/reference/threads#clearReplying); Go [`Threads.ClearReplying`](https://nextmail.sh/docs/go/reference/threads#clearReplying); Java [`threads().clearReplying`](https://nextmail.sh/docs/java/reference/threads#clearReplying); C# [`Threads.ClearReplyingAsync`](https://nextmail.sh/docs/csharp/reference/threads#clearReplying); CLI [`nextmail threads clear-replying`](https://nextmail.sh/docs/cli/reference/threads#threads-clear-replying).

### `threads.mark_done()`

Mark a thread done

```python
def mark_done(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadAssignmentResource
```

Archives the thread for everyone and records who marked it done. A new reply brings it back to the inbox, and `reopen` moves it back by hand.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadAssignmentResource` with `doneBy` and `doneAt`.

**Example**

```python
from nextmail import nextmail

assignment = nextmail.threads.mark_done('thr_8f2c41d0a3b94e6f')

print(assignment['doneAt'])
```

Also available in: API [`POST /threads/{id}/done`](https://nextmail.sh/docs/api/reference/team-inbox#post-threads-id-done); TypeScript [`threads.markDone()`](https://nextmail.sh/docs/sdk/reference/threads#markDone); Ruby [`threads.mark_done`](https://nextmail.sh/docs/ruby/reference/threads#markDone); PHP [`threads->markDone`](https://nextmail.sh/docs/php/reference/threads#markDone); Go [`Threads.MarkDone`](https://nextmail.sh/docs/go/reference/threads#markDone); Java [`threads().markDone`](https://nextmail.sh/docs/java/reference/threads#markDone); C# [`Threads.MarkDoneAsync`](https://nextmail.sh/docs/csharp/reference/threads#markDone); CLI [`nextmail threads mark-done`](https://nextmail.sh/docs/cli/reference/threads#threads-mark-done).

### `threads.reopen()`

Reopen a thread

```python
def reopen(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadAssignmentResource
```

Moves a done thread back to the inbox for everyone.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadAssignmentResource` with `doneBy` and `doneAt` set to `None`.

**Example**

```python
from nextmail import nextmail

assignment = nextmail.threads.reopen('thr_8f2c41d0a3b94e6f')

print(assignment['doneAt'])
```

Also available in: API [`POST /threads/{id}/reopen`](https://nextmail.sh/docs/api/reference/team-inbox#post-threads-id-reopen); TypeScript [`threads.reopen()`](https://nextmail.sh/docs/sdk/reference/threads#reopen); Ruby [`threads.reopen`](https://nextmail.sh/docs/ruby/reference/threads#reopen); PHP [`threads->reopen`](https://nextmail.sh/docs/php/reference/threads#reopen); Go [`Threads.Reopen`](https://nextmail.sh/docs/go/reference/threads#reopen); Java [`threads().reopen`](https://nextmail.sh/docs/java/reference/threads#reopen); C# [`Threads.ReopenAsync`](https://nextmail.sh/docs/csharp/reference/threads#reopen); CLI [`nextmail threads reopen`](https://nextmail.sh/docs/cli/reference/threads#threads-reopen).

### `threads.list_comments()`

List the comments on a thread

```python
def list_comments(
    id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> builtins.list[ThreadCommentResource]
```

Returns the team comments on one thread, oldest first. Everyone who can see the thread reads them, and the sender never does.

Scopes: `threads:read`.

**Parameters**

- `id` (`str`, required): Thread id.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`list[ThreadCommentResource]`, each with `id`, `threadId`, `author`, `body`, `mentions`, `createdAt` and `editedAt`.

**Example**

```python
from nextmail import nextmail

comments = nextmail.threads.list_comments('thr_8f2c41d0a3b94e6f')

for comment in comments:
    author = comment['author']
    print(author['email'] if author else 'removed', comment['body'])
```

**Notes**

- A thread delivered to no address the key covers is a 404.

Also available in: API [`GET /threads/{id}/comments`](https://nextmail.sh/docs/api/reference/team-inbox#get-threads-id-comments); TypeScript [`threads.listComments()`](https://nextmail.sh/docs/sdk/reference/threads#listComments); Ruby [`threads.list_comments`](https://nextmail.sh/docs/ruby/reference/threads#listComments); PHP [`threads->listComments`](https://nextmail.sh/docs/php/reference/threads#listComments); Go [`Threads.ListComments`](https://nextmail.sh/docs/go/reference/threads#listComments); Java [`threads().listComments`](https://nextmail.sh/docs/java/reference/threads#listComments); C# [`Threads.ListCommentsAsync`](https://nextmail.sh/docs/csharp/reference/threads#listComments); CLI [`nextmail threads list-comments`](https://nextmail.sh/docs/cli/reference/threads#threads-list-comments).

### `threads.create_comment()`

Comment on a thread

```python
def create_comment(
    id: str,
    body: ThreadCommentCreate,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadCommentResource
```

Adds a comment for the team. Everybody in `mentions` is emailed.

Only people who can see a thread can be given it or mentioned on it: the workspace owner, members who reach every address, and members who hold its address or its domain. A key acts for the workspace owner.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `body['body']` (`str`, required): What the comment says, up to 10,000 characters. Leading and trailing spaces are trimmed.
- `body['mentions']` (`list[str]`): The user ids of people to mention, at most 20. Each has to be able to see the thread.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadCommentResource` for the new comment.

**Example**

```python
from nextmail import nextmail

comment = nextmail.threads.create_comment(
    'thr_8f2c41d0a3b94e6f',
    {'body': 'Can you take this one?', 'mentions': ['usr_2f9c1d']},
)

print(comment['id'])
```

**Notes**

- The SDK does not retry it, because a second call would add a second comment.
- Somebody in `mentions` who cannot see the thread is a 422 `invalid_parameter` on `mentions`.

Also available in: API [`POST /threads/{id}/comments`](https://nextmail.sh/docs/api/reference/team-inbox#post-threads-id-comments); TypeScript [`threads.createComment()`](https://nextmail.sh/docs/sdk/reference/threads#createComment); Ruby [`threads.create_comment`](https://nextmail.sh/docs/ruby/reference/threads#createComment); PHP [`threads->createComment`](https://nextmail.sh/docs/php/reference/threads#createComment); Go [`Threads.CreateComment`](https://nextmail.sh/docs/go/reference/threads#createComment); Java [`threads().createComment`](https://nextmail.sh/docs/java/reference/threads#createComment); C# [`Threads.CreateCommentAsync`](https://nextmail.sh/docs/csharp/reference/threads#createComment); CLI [`nextmail threads create-comment`](https://nextmail.sh/docs/cli/reference/threads#threads-create-comment).

### `threads.update_comment()`

Change a comment

```python
def update_comment(
    id: str,
    comment_id: str,
    body: ThreadCommentCreate,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> ThreadCommentResource
```

Replaces the text and the mentions of a comment. Only its author can change it, and anybody newly mentioned is emailed.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `comment_id` (`str`, required): The comment id, as `list_comments` returns it.
- `body['body']` (`str`, required): The new text, up to 10,000 characters.
- `body['mentions']` (`list[str]`): The user ids it mentions now, at most 20. Leave it out to mention nobody.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`ThreadCommentResource` as it is now.

**Example**

```python
from nextmail import nextmail

comment = nextmail.threads.update_comment(
    'thr_8f2c41d0a3b94e6f', 'tcm_8a1f', {'body': 'Done, sent the quote.'}
)

print(comment['editedAt'])
```

**Notes**

- Someone else's comment, or one on another thread, is a 404.

Also available in: API [`PATCH /threads/{id}/comments/{commentId}`](https://nextmail.sh/docs/api/reference/team-inbox#patch-threads-id-comments-commentid); TypeScript [`threads.updateComment()`](https://nextmail.sh/docs/sdk/reference/threads#updateComment); Ruby [`threads.update_comment`](https://nextmail.sh/docs/ruby/reference/threads#updateComment); PHP [`threads->updateComment`](https://nextmail.sh/docs/php/reference/threads#updateComment); Go [`Threads.UpdateComment`](https://nextmail.sh/docs/go/reference/threads#updateComment); Java [`threads().updateComment`](https://nextmail.sh/docs/java/reference/threads#updateComment); C# [`Threads.UpdateCommentAsync`](https://nextmail.sh/docs/csharp/reference/threads#updateComment); CLI [`nextmail threads update-comment`](https://nextmail.sh/docs/cli/reference/threads#threads-update-comment).

### `threads.delete_comment()`

Delete a comment

```python
def delete_comment(
    id: str,
    comment_id: str,
    *,
    api_key: str | None = None,
    timeout: float | None = None,
) -> DeletedThreadCommentResource
```

Deletes a comment for good. Its author can delete it, and so can the workspace owner, which a key acts for.

Scopes: `threads:write`.

**Parameters**

- `id` (`str`, required): Thread id.
- `comment_id` (`str`, required): The comment id, as `list_comments` returns it.
- `api_key` (`str`): Overrides the client's API key for this call only.
- `timeout` (`float`): Seconds this call may take, the response included, before it raises `NextmailNetworkError` with `is_timeout`. It overrides the client's `timeout` for this call, and `0` turns the limit off.

**Returns**

`DeletedThreadCommentResource` with `object` set to `thread_comment`, the `id` and `threadId`, and `deleted` set to `True`.

**Example**

```python
from nextmail import nextmail

deleted = nextmail.threads.delete_comment('thr_8f2c41d0a3b94e6f', 'tcm_8a1f')

print(deleted['id'], deleted['deleted'])
```

**Notes**

- The SDK does not retry a delete. A 404 on your own second attempt after a lost response means the first one worked.

Also available in: API [`DELETE /threads/{id}/comments/{commentId}`](https://nextmail.sh/docs/api/reference/team-inbox#delete-threads-id-comments-commentid); TypeScript [`threads.deleteComment()`](https://nextmail.sh/docs/sdk/reference/threads#deleteComment); Ruby [`threads.delete_comment`](https://nextmail.sh/docs/ruby/reference/threads#deleteComment); PHP [`threads->deleteComment`](https://nextmail.sh/docs/php/reference/threads#deleteComment); Go [`Threads.DeleteComment`](https://nextmail.sh/docs/go/reference/threads#deleteComment); Java [`threads().deleteComment`](https://nextmail.sh/docs/java/reference/threads#deleteComment); C# [`Threads.DeleteCommentAsync`](https://nextmail.sh/docs/csharp/reference/threads#deleteComment); CLI [`nextmail threads delete-comment`](https://nextmail.sh/docs/cli/reference/threads#threads-delete-comment).

### `threads.wait_for_email()`

Wait for a message to arrive

```python
def wait_for_email(
    *,
    address: str | None = None,
    from_: str | None = None,
    subject: str | None = None,
    since: datetime | str | None = None,
    timeout: int | None = None,
    api_key: str | None = None,
) -> MessageWaitResource
```

Holds the request open until a message that matches arrives, for at most `timeout` seconds, and returns the first one: the oldest match that arrived after `since`. It is how a script or an agent waits for a sign-in code after asking a service to send one. `from_` matches the sender's address or name and `subject` the subject, both as text anywhere in them and in any case, and `address` keeps only the mail delivered to that address. Mail the workspace sent itself never matches.

It returns a dict with `object` set to `message_wait`, `message` and `waitedMs`, where `message` holds `object` set to `message_arrival`, `threadId`, `messageId`, `address`, `from`, `subject` and `receivedAt`, or is `None` when nothing matched in time. Read the body with `threads.get_message(thread_id, message_id)`, or pass its subject and body to `tools.read_verification_code` to read a code out of it.

A key or an app limited to particular addresses waits only for mail to the addresses it reaches.

Scopes: `threads:read`.

**Parameters**

- `address` (`str`): Only mail delivered to this address. One the key does not reach matches nothing rather than failing.
- `from_` (`str`): Text the sender's address or name contains, such as `github.com`, sent as `from`. Matched in any case.
- `subject` (`str`): Text the subject contains, such as `verification code`. Matched in any case, at most 200 characters.
- `since` (`datetime | str`): Only mail that arrived at or after this moment, as a `datetime` or an ISO 8601 string, at most 24 hours ago. Left out, the moment the request arrives, so only new mail matches.
- `timeout` (`int`): How long to wait, in whole seconds from 0 to 60. Left out, 30, and `0` looks once and answers at once. It also sets how long the call itself may take: `timeout` plus 15 seconds, whatever the client's `timeout` is.
- `api_key` (`str`): Overrides the client's API key for this call only.

**Returns**

`MessageWaitResource`, a dict with `object` set to `message_wait`, `message` and `waitedMs`. `message` is a `MessageArrivalResource` with `object` set to `message_arrival`, `threadId`, `messageId`, `address`, `from`, a dict with `email` and `name`, `subject` and `receivedAt`, or `None` when the wait ran out.

**Example**

```python
from datetime import datetime, timezone

from nextmail import nextmail

asked_at = datetime.now(timezone.utc)
wait = nextmail.threads.wait_for_email(
    address='agent@example.com', from_='github.com', subject='code', since=asked_at, timeout=60
)
arrival = wait['message']

if arrival is None:
    print('Nothing arrived in', wait['waitedMs'], 'ms')
else:
    message = nextmail.threads.get_message(arrival['threadId'], arrival['messageId'])
    read = nextmail.tools.read_verification_code(
        {'subject': message['subject'], 'html': message['html'] or ''}
    )

    print(arrival['from']['email'], read['code'])
```

**Notes**

- The SDK gives this call a deadline of `timeout` plus 15 seconds, so a long wait is not cut short by the client's `timeout`.
- Read only, so the SDK retries it after a network failure like any other read.

Also available in: API [`GET /threads/wait`](https://nextmail.sh/docs/api/reference/threads#get-threads-wait); TypeScript [`threads.waitForEmail()`](https://nextmail.sh/docs/sdk/reference/threads#waitForEmail); Ruby [`threads.wait_for_email`](https://nextmail.sh/docs/ruby/reference/threads#waitForEmail); PHP [`threads->waitForEmail`](https://nextmail.sh/docs/php/reference/threads#waitForEmail); Go [`Threads.WaitForEmail`](https://nextmail.sh/docs/go/reference/threads#waitForEmail); Java [`threads().waitForEmail`](https://nextmail.sh/docs/java/reference/threads#waitForEmail); C# [`Threads.WaitForEmailAsync`](https://nextmail.sh/docs/csharp/reference/threads#waitForEmail); CLI [`nextmail threads wait-for-email`](https://nextmail.sh/docs/cli/reference/threads#threads-wait-for-email).
