IMAP
IMAP is the protocol most mail clients use to keep a mailbox in step between the server and each of the user’s devices. Unlike POP3, it leaves the mail on the server: a client lists the folders, fetches what it needs, sets flags and moves messages, and every change is visible to the user’s other clients. Stalwart implements IMAP4rev2 (RFC 9051) and IMAP4rev1 (RFC 3501), together with the extensions that current clients rely on for synchronisation, search and push.
IMAP sessions are long-lived and driven by clients the administrator does not control, so the server also needs rules for how clients authenticate, how long idle sessions last and how much work one command may cause. These settings are held by the Imap singleton, found in the WebUI under Settings › Network › IMAP. The same singleton also governs POP3, and its authentication and session settings apply to ManageSieve as well. Listeners, ports and TLS are configured on each NetworkListener, as described in the protocol overview.
Protocol versions
Section titled “Protocol versions”A session starts as IMAP4rev1, the version that every client understands. A client that implements IMAP4rev2 switches to it with ENABLE IMAP4rev2, which also turns on UTF-8 mailbox names and headers for the session. The server greets every client with * OK [CAPABILITY ...] Stalwart IMAP4rev2 at your service., a fixed text that carries the capability list.
ENABLE also turns on the extensions that change how the server responds, and the server reports in * ENABLED the ones it turned on:
CONDSTOREandQRESYNC, for incremental synchronisation;QRESYNCimpliesCONDSTOREUTF8=ACCEPT, for UTF-8 in mailbox names and message headersOBJECTID+, for the stable identifiers of messages, threads and mailboxes; it is also turned on implicitly when a command asks for one of themUIDONLY, which replaces message sequence numbers with UIDs in every response
Names the server does not know are ignored without error, as the specification requires. One client is treated differently: a client that identifies itself with the ID command as Microsoft Office 365 is never given UIDONLY, which is left out of the * ENABLED response.
Capabilities
Section titled “Capabilities”Before authentication, the server lists IMAP4rev2, IMAP4rev1, ENABLE, SASL-IR, LITERAL+, ID and UTF8=ACCEPT, followed by the authentication mechanisms described in Authentication and, on a cleartext connection to a listener that has TLS available, STARTTLS. After authentication, the tagged OK of the login carries the full list, which no longer includes the authentication mechanisms:
| Capability | Specification | Purpose |
|---|---|---|
IDLE | RFC 2177 | Push of changes to the open mailbox, described in IDLE. |
NAMESPACE | RFC 2342 | Personal and shared folder prefixes. |
CHILDREN, LIST-EXTENDED, LIST-STATUS | RFC 3348, RFC 5258, RFC 5819 | Folder listing with child information and status in one command. |
SPECIAL-USE, CREATE-SPECIAL-USE | RFC 6154 | Folder roles such as Sent and Trash. |
MULTIAPPEND, UIDPLUS, MOVE | RFC 3502, RFC 4315, RFC 6851 | Uploading several messages at once, the UIDs of stored messages, atomic moves. |
BINARY, PREVIEW, STATUS=SIZE | RFC 3516, RFC 8970, RFC 8438 | Decoded message parts, text previews, mailbox sizes. |
UNSELECT, UNAUTHENTICATE | RFC 3691, RFC 8437 | Closing a mailbox without expunging, ending the login without closing the connection. |
ACL, RIGHTS=texkn | RFC 4314 | Mailbox sharing, described in Shared mailboxes. |
ESEARCH, WITHIN, SEARCHRES | RFC 4731, RFC 5032, RFC 5182 | Compact search results, date ranges, reuse of the last result. |
SORT, ESORT, SORT=DISPLAY, THREAD=REFERENCES | RFC 5256, RFC 5267, RFC 5957 | Server-side sorting and threading, described in Search, sorting and threads. |
CONDSTORE, QRESYNC | RFC 7162 | Incremental synchronisation, described in Synchronisation. |
OBJECTID+ | draft-ietf-mailmaint-imap-objectid-bis | Stable message, thread and mailbox identifiers, the same as in JMAP. |
UIDONLY, UIDBATCHES | RFC 9586, RFC 10022 | UIDs in place of sequence numbers, paging through large mailboxes. |
MESSAGELIMIT, SAVELIMIT | RFC 9738 | Announced command limits, described in Message limits. |
QUOTA, QUOTA=RES-STORAGE | RFC 9208 | Storage quota of the account, described in Quotas. |
JMAPACCESS | RFC 9698 | Discovery of the JMAP endpoint for the same account. |
METADATA, LIST-METADATA | RFC 5464, RFC 9590 | Annotations, listed only to accounts that may read them, as described in METADATA. |
Some extensions that clients may probe for are not implemented: COMPRESS, NOTIFY, CATENATE, URLAUTH and QUOTA=SET. A command from one of them is answered with BAD, and quotas are changed by the administrator, as described in Quotas, not by clients. RFCs lists every specification Stalwart implements.
JMAPACCESS lets a client that starts with IMAP discover that the same account is reachable over JMAP. The GETJMAPACCESS command returns the URL of the JMAP session resource, built from the server’s public URL, for example * JMAPACCESS "https://mail.example.com/.well-known/jmap".
Authentication
Section titled “Authentication”A password sent over a cleartext connection can be read by anyone on the network path. Whether credentials may cross an unencrypted connection is therefore a setting, allowPlainTextAuth, which is disabled unless it is changed. A client on a cleartext connection must therefore first upgrade it with STARTTLS (or STLS in POP3).
Repeated failures are also bounded. A client that keeps failing to sign in is disconnected after maxAuthFailures failed attempts in one session, 3 by default.
Clients see the setting in the responses they receive. While allowPlainTextAuth is disabled, no SASL mechanism is offered on a cleartext connection. IMAP announces LOGINDISABLED in its capability list, answers LOGIN with NO LOGIN is disabled on the clear-text port., and answers an AUTHENTICATE command with NO [PRIVACYREQUIRED] Cannot authenticate over plain-text. POP3 behaves in the same way with its own replies, as described in POP3 authentication. Where authentication is allowed, IMAP offers LOGIN and the SASL mechanism PLAIN; mechanisms other than those described here are refused with NO [CANNOT] Authentication mechanism not supported.
allowPlainTextAuth covers password mechanisms only. Tokens follow a stricter rule. The OAUTHBEARER and XOAUTH2 mechanisms, which carry an OAuth access token or an API key in place of a password, are advertised and accepted only on TLS connections, whatever the value of the setting. The same rule applies to SMTP and ManageSieve. TLS on the mail protocols lists the responses a client receives on a cleartext connection. A token must also carry the mail scope to be accepted for these protocols.
Behind a TLS-terminating proxy, the server cannot see the TLS session itself. A connection forwarded by such a proxy counts as encrypted only when the proxy sends a PROXY protocol version 2 header with the SSL TLV.
The check is skipped in bootstrap mode, which runs the setup wizard on a new installation, and recovery mode, the maintenance mode for repairing a configuration. Mail, calendar and contacts clients describes which clients can use OAuth.
The number of connections and requests an account may open is limited separately, as described in Session limits.
Folders and namespaces
Section titled “Folders and namespaces”IMAP names folders by path. Stalwart uses / as the hierarchy delimiter, and the account’s own folders sit at the top level, with no prefix, so the personal namespace is "". INBOX is matched without regard to case, as the protocol requires. Every LIST response carries the special-use attributes, such as \Sent and \Trash, whether or not the client asked for them, because many clients depend on them to find their folders. The folders created for new accounts, and the aliases that let clients find them under other names, are described in Default folders.
Mailboxes that other accounts share with the user appear under a virtual folder, Shared Folders unless renamed, followed by the owner’s address and the mailbox path, for example Shared Folders/[email protected]/Projects. The same applies to the mailboxes of the groups the user belongs to. The NAMESPACE command reports the shared prefix only when the user has access to at least one such account, and answers * NAMESPACE (("" "/")) NIL NIL otherwise. Shared mailboxes describes the rights involved.
A message that is filed in several folders, which JMAP clients can do, appears in each of those folders with a UID of its own and the same flags. Mailboxes, messages and flags describes what this means for flags, expunging and the junk-mail flags that train the spam classifier.
Synchronisation
Section titled “Synchronisation”A client that opens a mailbox it has seen before needs to learn only what has changed since. Stalwart implements CONDSTORE and QRESYNC (RFC 7162) for this: each change to a message carries a modification sequence, a client asks for the changes since the last sequence it saw, and with QRESYNC it also learns which messages were expunged, through VANISHED responses, without fetching the whole UID list again. The server answers from the change history of the account, whose length is bounded by maxChangesHistory. A client that has been away for longer than the history reaches has to fetch the state of the mailbox again.
Two further extensions make synchronisation cheaper. UIDONLY replaces message sequence numbers with UIDs, so the client no longer needs to track sequence numbers that shift with every expunge, and expunges are then reported with VANISHED as well. OBJECTID+ gives every message, thread and mailbox a stable identifier, the same one that JMAP uses, so a client can recognise a message that was moved to another folder instead of downloading it again.
Message UIDs stay valid for as long as the mailbox exists, and UIDVALIDITY changes only when the administrator reassigns the UIDs of an account, as described in Message UIDs.
A client that selects a mailbox while another one is selected first receives * OK [CLOSED] Closed previous mailbox, the response code QRESYNC defines, so that it knows which responses belong to which mailbox. The previous mailbox is closed even when the new SELECT or EXAMINE fails, and the session is then left with no mailbox selected.
IDLE (RFC 2177) lets a client wait for changes instead of polling. The server answers + Idling, send 'DONE' to stop. and from then on reports changes as they happen: new and expunged messages and flag changes in the selected mailbox, and changes to the folder list. Changes are pushed by the server the moment they are stored, whichever protocol made them, so a message delivered over SMTP or moved by a JMAP client reaches an idling IMAP client at once. Changes to the folder lists of groups the user belongs to are also reported, at most once per second.
While a client idles, and when it sends NOOP, mailboxes whose contents changed are reported as unsolicited STATUS responses with the message count, the unseen count, UIDNEXT and UIDVALIDITY. For a client that has enabled CONDSTORE, they also carry HIGHESTMODSEQ, so the client can tell whether the mailbox needs a resynchronisation without selecting it.
The client ends the command with DONE. A client that idles for longer than idleTimeout receives * BYE IDLE timed out. and is disconnected, as described in Timeouts. Clients normally restart IDLE well before that, since the protocol expects them to.
IDLE covers one mailbox per connection. Clients that watch several folders open a connection for each, which counts towards the account’s session limit.
Search, sorting and threads
Section titled “Search, sorting and threads”Searches cover the message headers and body, and also the text of attachments in common document formats, as described in Attachment text extraction. Search terms are expected in UTF-8. A CHARSET that the server does not recognise is treated as UTF-8 rather than refused, and a search term that is not valid UTF-8 is answered with BAD Invalid UTF-8 argument.
SORT accepts the criteria ARRIVAL, CC, DATE, FROM, SIZE, SUBJECT and TO of RFC 5256, and DISPLAYFROM and DISPLAYTO of RFC 5957, each optionally preceded by REVERSE.
THREAD returns the threads that the server computed when the messages arrived, the same threads that JMAP clients see. Threads describes how messages are grouped. The response lists each thread as a flat group of messages, for example * THREAD (1 2 3)(4 5), without the reply tree that RFC 5256 describes. The server advertises the REFERENCES algorithm, and also accepts ORDEREDSUBJECT, which returns the same groups.
Quotas
Section titled “Quotas”The QUOTA extension (RFC 9208) lets a client show how much of the account’s storage is used. Stalwart reports the STORAGE resource of the account’s quota, for the account itself and for shared accounts the user is a member of. An account without a storage quota has no limit to report, and its quota root carries no resource. Quotas cannot be set over IMAP.
Timeouts
Section titled “Timeouts”Idle sessions hold resources on the server, so the server closes a session that stays inactive for longer than its timeout. Each timeout is a duration in milliseconds, and the one that applies depends on the state of the session:
| Field | Default | Applies to |
|---|---|---|
anonymousTimeout | 1 minute | Sessions that have not authenticated. |
authenticatedTimeout | 30 minutes | Authenticated sessions. |
idleTimeout | 30 minutes | IMAP sessions in the IDLE state. |
The protocol constrains how low the timeouts for authenticated sessions may go. RFC 9051 requires an inactivity timer of at least 30 minutes for authenticated IMAP sessions. Lowering authenticatedTimeout or idleTimeout below that value therefore disconnects clients that are behaving correctly. The timeout for unauthenticated sessions has no such constraint, and the following object body shortens it:
{ "anonymousTimeout": 30000}Request size
Section titled “Request size”An IMAP command can carry data of its own, called a literal, and a literal can be large. The largest IMAP command the server accepts, literals included, is set in bytes by maxRequestSize, 50 MiB unless changed. Because APPEND carries the message as a literal, this value also caps the size of a message uploaded over IMAP.
Unauthenticated clients get far less. Before a client has authenticated, the limit is a fixed 64 KiB, and a larger literal closes the connection with * BYE [TOOBIG] Literal exceeds the maximum size allowed before authentication. After authentication, a literal larger than maxRequestSize is refused with the TOOBIG response code. The size limits that apply to every protocol are described in Message and mailbox limits.
Memory is a separate constraint. A command that needs more memory than the server can currently grant fails with NO [UNAVAILABLE], and the client may retry it later. The memory budget is described in Sizing memory.
Command limits
Section titled “Command limits”Some parts of a command can be repeated without bound in the syntax, and an oversized list makes the server parse and evaluate far more than any client needs. The server therefore caps them, and a command over a cap is refused with a tagged BAD that names the problem:
| Part of the command | Limit | Response |
|---|---|---|
Data items requested by one FETCH | 128 | Too many fetch attributes. |
Header field names in the HEADER.FIELDS and HEADER.FIELDS.NOT sections of one FETCH, all sections together | 256 | Too many header field names. |
| Search keys in the search criteria of one command, parentheses included | 256 | Too many search criteria. |
| Items of one sequence set, in any command that takes one | 4096 | Too many items in sequence set. |
Flags of one STORE or APPEND | 128 | Too many flags. |
A sequence set counts its comma-separated items, so a single range such as 1:* counts as one item however many messages it covers. Ranges that overlap are merged before the messages are looked up. The limits are fixed and cannot be configured.
Message limits
Section titled “Message limits”A single IMAP command can address every message in a mailbox, which on a very large mailbox means a great deal of work. Two fields bound the number of messages that a single IMAP command processes. Both are announced to clients through the MESSAGELIMIT extension (RFC 9738), so a client that implements it can page through a large mailbox.
| Field | Default | Commands |
|---|---|---|
maxMessagesPerCommand | 1000000, minimum 1000 | FETCH, SEARCH, STORE, MOVE and UID EXPUNGE, announced as MESSAGELIMIT. |
maxMessagesPerSave | 1000000, minimum 1000 | COPY and APPEND, announced as SAVELIMIT. |
The two limits behave differently when they are reached. When a command exceeds maxMessagesPerCommand, the messages with the highest UIDs are processed, and the tagged OK carries a MESSAGELIMIT response code naming the lowest UID that was handled. The client can then continue from there. COPY and APPEND, by contrast, are atomic, so a command over maxMessagesPerSave stores nothing and fails with a tagged NO. EXPUNGE and CLOSE are never limited. Keep maxMessagesPerSave at or above maxMessagesPerCommand.
The defaults are higher than the size of any realistic mailbox, so the limits normally have no effect. Lowering them has a cost for clients that do not implement RFC 9738: they receive partial results from FETCH and SEARCH, and see COPY and APPEND fail. Reduce the limits only when a specific workload requires it.
UID batches
Section titled “UID batches”Paging through a large mailbox is easier when the client knows where each page begins. The UIDBATCHES extension (RFC 10022) allows a client to ask the server to split the selected mailbox into batches of equal size, and to return the UID range of each batch. The client can then paginate a large mailbox without message sequence numbers. Two fields bound the requests:
| Field | Default | Limit |
|---|---|---|
minUidBatchSize | 500, maximum 500 | Smallest batch size a client may request. Smaller requests are rejected with the TOOFEW response code. |
maxUidBatches | 10000 | Largest number of UID ranges returned by one command. Wider requests are rejected with the TOOMANY response code. |
The specification requires servers to support a batch size of 500, which is why minUidBatchSize cannot exceed that value. The minimum batch size has a second purpose. The UIDONLY extension (RFC 9586) replaces message sequence numbers with UIDs in responses, and very small batches would let a client reconstruct the sequence numbers while UIDONLY is in effect. The minimum prevents this. At the defaults, maxUidBatches covers a mailbox of five million messages.
METADATA
Section titled “METADATA”Some clients store settings of their own on the server, such as a mailbox colour or a comment. IMAP METADATA (RFC 5464) provides this, by storing annotations on mailboxes and on the server. LIST-METADATA (RFC 9590) returns annotations in LIST responses. Stalwart implements both.
The METADATA and LIST-METADATA capabilities are advertised after login, to accounts that hold the imapMetadataGet permission. Annotations are stored as object metadata. They are shared with JMAP and WebDAV, and subject to the size limits described in Object metadata.
Permissions
Section titled “Permissions”Each IMAP command is governed by a permission of its own, such as imapSelect, imapFetch, imapAppend or imapMove, and signing in at all requires imapAuthenticate. Removing imapAuthenticate from a role withdraws IMAP from its users without affecting their other protocols; removing a narrower permission disables a single command, for example imapMetadataSet to make annotations read-only. The full list is in the permissions reference.