RFC 3501
INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1
RFC 3501: INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1 ๐
Okay bestie, let's get the basics down first ๐. This is RFC 3501, titled INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1. It came out of the Network Working Group in March 2003, written by M. Crispin from the University of Washington. It's on the Standards Track ๐ฆ, and it obsoletes RFC 2060 ๐ . The header doesn't say it updates anything.
Status of this Memo โจ
So this doc is an Internet standards track protocol for the Internet community, and it's asking for discussion and suggestions to make it better ๐ซถ. If you want to know where this protocol stands in the standardization process, check the current edition of the "Internet Official Protocol Standards" (STD 1) ๐. And distribution of this memo is unlimited, so share it with everyone ๐ธ.
Copyright Notice ๐ฅ
Copyright (C) The Internet Society (2003). All Rights Reserved.
Abstract ๐ฆ
Okay so IMAP4rev1 (the Internet Message Access Protocol, Version 4rev1) is how a client gets to read and manage email sitting on a server ๐. It lets you manipulate mailboxes (basically remote message folders) in a way that works just like local folders, which is iconic ๐. It also gives an offline client a way to resynchronize with the server ๐.
The protocol has operations for making, deleting, and renaming mailboxes, checking for new messages, permanently removing messages, setting and clearing flags, parsing RFC 2822 and RFC 2045 content, searching, and selectively fetching message attributes, texts, and portions of them ๐โจ. Messages get accessed by numbers, and those numbers are either message sequence numbers or unique identifiers ๐ข.
IMAP4rev1 is built for a single server ๐ฅ๏ธ. If you need a way to access configuration info for multiple IMAP4rev1 servers, that's covered in RFC 2244 ๐ง.
Also, IMAP4rev1 does NOT specify how to post mail ๐ โโ๏ธ. That's handled by a mail transfer protocol, like RFC 2821 ๐.
Table of Contents ๐
IMAP4rev1 Protocol Specification ................................ 4
1. How to Read This Document ............................... 4
1.1. Organization of This Document ........................... 4
1.2. Conventions Used in This Document ....................... 4
1.3. Special Notes to Implementors ........................... 5
2. Protocol Overview ....................................... 6
2.1. Link Level .............................................. 6
2.2. Commands and Responses .................................. 6
2.2.1. Client Protocol Sender and Server Protocol Receiver ..... 6
2.2.2. Server Protocol Sender and Client Protocol Receiver ..... 7
2.3. Message Attributes ...................................... 8
2.3.1. Message Numbers ......................................... 8
2.3.1.1. Unique Identifier (UID) Message Attribute ....... 8
2.3.1.2. Message Sequence Number Message Attribute ....... 10
2.3.2. Flags Message Attribute ................................. 11
2.3.3. Internal Date Message Attribute ......................... 12
2.3.4. [RFC-2822] Size Message Attribute ....................... 12
2.3.5. Envelope Structure Message Attribute .................... 12
2.3.6. Body Structure Message Attribute ........................ 12
2.4. Message Texts ........................................... 13
3. State and Flow Diagram .................................. 13
3.1. Not Authenticated State ................................. 13
3.2. Authenticated State ..................................... 13
3.3. Selected State .......................................... 13
3.4. Logout State ............................................ 14
4. Data Formats ............................................ 16
4.1. Atom .................................................... 16
4.2. Number .................................................. 16
4.3. String .................................................. 16
4.3.1. 8-bit and Binary Strings ................................ 17
4.4. Parenthesized List ...................................... 17
4.5. NIL ..................................................... 17
5. Operational Considerations .............................. 18
5.1. Mailbox Naming .......................................... 18
5.1.1. Mailbox Hierarchy Naming ................................ 19
5.1.2. Mailbox Namespace Naming Convention ..................... 19
5.1.3. Mailbox International Naming Convention ................. 19
5.2. Mailbox Size and Message Status Updates ................. 21
5.3. Response when no Command in Progress .................... 21
5.4. Autologout Timer ........................................ 22
5.5. Multiple Commands in Progress ........................... 22
6. Client Commands ........................................ 23
6.1. Client Commands - Any State ............................ 24
6.1.1. CAPABILITY Command ..................................... 24
6.1.2. NOOP Command ........................................... 25
6.1.3. LOGOUT Command ......................................... 26
6.2. Client Commands - Not Authenticated State .............. 26
6.2.1. STARTTLS Command ....................................... 27
6.2.2. AUTHENTICATE Command ................................... 28
6.2.3. LOGIN Command .......................................... 30
6.3. Client Commands - Authenticated State .................. 31
6.3.1. SELECT Command ......................................... 32
6.3.2. EXAMINE Command ........................................ 34
6.3.3. CREATE Command ......................................... 34
6.3.4. DELETE Command ......................................... 35
6.3.5. RENAME Command ......................................... 37
6.3.6. SUBSCRIBE Command ...................................... 39
6.3.7. UNSUBSCRIBE Command .................................... 39
6.3.8. LIST Command ........................................... 40
6.3.9. LSUB Command ........................................... 43
6.3.10. STATUS Command ......................................... 44
6.3.11. APPEND Command ......................................... 46
6.4. Client Commands - Selected State ....................... 47
6.4.1. CHECK Command .......................................... 47
6.4.2. CLOSE Command .......................................... 48
6.4.3. EXPUNGE Command ........................................ 49
6.4.4. SEARCH Command ......................................... 49
6.4.5. FETCH Command .......................................... 54
6.4.6. STORE Command .......................................... 58
6.4.7. COPY Command ........................................... 59
6.4.8. UID Command ............................................ 60
6.5. Client Commands - Experimental/Expansion ............... 62
6.5.1. X<atom> Command ........................................ 62
7. Server Responses ....................................... 62
7.1. Server Responses - Status Responses .................... 63
7.1.1. OK Response ............................................ 65
7.1.2. NO Response ............................................ 66
7.1.3. BAD Response ........................................... 66
7.1.4. PREAUTH Response ....................................... 67
7.1.5. BYE Response ........................................... 67
7.2. Server Responses - Server and Mailbox Status ........... 68
7.2.1. CAPABILITY Response .................................... 68
7.2.2. LIST Response .......................................... 69
7.2.3. LSUB Response .......................................... 70
7.2.4 STATUS Response ........................................ 70
7.2.5. SEARCH Response ........................................ 71
7.2.6. FLAGS Response ......................................... 71
7.3. Server Responses - Mailbox Size ........................ 71
7.3.1. EXISTS Response ........................................ 71
7.3.2. RECENT Response ........................................ 72
7.4. Server Responses - Message Status ...................... 72
7.4.1. EXPUNGE Response ....................................... 72
7.4.2. FETCH Response ......................................... 73
7.5. Server Responses - Command Continuation Request ........ 79
8. Sample IMAP4rev1 connection ............................ 80
9. Formal Syntax .......................................... 81
10. Author's Note .......................................... 92
11. Security Considerations ................................ 92
11.1. STARTTLS Security Considerations ....................... 92
11.2. Other Security Considerations .......................... 93
12. IANA Considerations .................................... 94
Appendices ..................................................... 95
A. References ............................................. 95
B. Changes from RFC 2060 .................................. 97
C. Key Word Index ......................................... 103
Author's Address ............................................... 107
Full Copyright Statement ....................................... 108
1. How to Read This Document โจ
1.1. Organization of This Document
okay so this doc is written from the point of view of the implementor ๐ of an IMAP4rev1 client or server. Beyond the protocol overview in section 2, it's not really optimized for someone trying to understand how the protocol works ๐ Sections 3 through 5 give you the general context and definitions that IMAP4rev1 operates with, so read those first bestie ๐ง
Sections 6, 7, and 9 cover the IMAP commands, responses, and syntax, respectively. These are so intertwined that it's almost impossible to understand any one of them on its own ๐ญ Like, do not try to figure out command syntax from the command section alone. Go to the Formal Syntax section instead ๐ซถ
1.2. Conventions Used in This Document
"Conventions" are basic principles or procedures, and this is where the doc's own conventions get noted ๐
In examples, C: and S: mean lines sent by the client and server respectively ๐ฆ
The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [KEYWORDS]. these are the main-character words of the spec, so pay attention to them ๐
The word "can" (not "may") is used for a possible circumstance or situation, as opposed to an optional facility of the protocol ๐
"User" refers to a human, whereas "client" refers to the software the user is running ๐ธ
"Connection" means the entire sequence of client/server interaction, from when the network connection is first established until it gets terminated ๐
"Session" is the sequence of client/server interaction from the moment a mailbox is selected (SELECT or EXAMINE command) until that selection ends. And it ends when you SELECT or EXAMINE a different mailbox, send a CLOSE command, or the connection terminates โจ
Characters are 7-bit US-ASCII unless otherwise specified. Other character sets are indicated using a "CHARSET", as described in [MIME-IMT] and defined in [CHARSET]. CHARSETs have important additional semantics beyond just defining a character set, so go check those documents for the tea โ
There are several protocol conventions in IMAP. These aren't strictly part of the IMAP protocol, but they reflect generally-accepted practice. Implementations need to be aware of them and avoid conflicts, whether or not they implement the convention. For example, & may not be used as a hierarchy delimiter since it conflicts with the Mailbox International Naming Convention, and other uses of & in mailbox names are impacted as well ๐
1.3. Special Notes to Implementors
Implementors of the IMAP protocol are strongly encouraged to read the IMAP implementation recommendations document [IMAP-IMPLEMENTATION] alongside this one. It helps you understand the intricacies of the protocol and how to build an interoperable product, which is honestly the goal ๐
IMAP4rev1 is designed to be upwards compatible from the [IMAP2] and unpublished IMAP2bis protocols ๐ฆ It's also largely compatible with the IMAP4 protocol described in RFC 1730. The exception is certain facilities that were added in RFC 1730, proved problematic, and were later removed. Over the evolution of IMAP4rev1, some aspects of the earlier protocols became obsolete. Obsolete commands, responses, and data formats that an IMAP4rev1 implementation can run into when working with an earlier implementation are described in [IMAP-OBSOLETE] ๐ฐ๏ธ
Other compatibility issues with IMAP2bis, the most common variant of the earlier protocol, are discussed in [IMAP-COMPAT]. A full discussion of compatibility with rare (and presumed extinct) variants of [IMAP2] is in [IMAP-HISTORICAL]. That one is primarily of historical interest ๐
IMAP was originally developed for the older [RFC-822] standard, so a bunch of fetch items have "RFC822" in their name. With the exception of RFC822.SIZE, there are more modern replacements. For example, the modern version of RFC822.HEADER is BODY.PEEK[HEADER] โจ In all cases, "RFC822" should be interpreted as a reference to the updated [RFC-2822] standard ๐
2. Protocol Overview ๐
2.1. Link Level
The IMAP4rev1 protocol assumes a reliable data stream, like the one provided by TCP ๐ง When TCP is used, an IMAP4rev1 server listens on port 143 ๐ฆ
2.2. Commands and Responses
An IMAP4rev1 connection is made up of three things: the establishment of a client/server network connection, an initial greeting from the server, and client/server interactions. Those interactions consist of a client command, server data, and a server completion result response ๐ฅ
All interactions sent by the client and server are in the form of lines, meaning strings that end with a CRLF. The protocol receiver of an IMAP4rev1 client or server is either reading a line, or reading a sequence of octets with a known count followed by a line ๐
2.2.1. Client Protocol Sender and Server Protocol Receiver
The client command kicks off an operation ๐ Each client command is prefixed with an identifier (typically a short alphanumeric string, e.g., A0001, A0002, etc.) called a "tag". The client generates a different tag for each command ๐
Clients MUST follow the syntax outlined in this specification strictly. Sending a command with missing or extraneous spaces or arguments is a syntax error, so no sloppy vibes allowed ๐ญ
There are two cases where a line from the client does not represent a complete command. In one case, a command argument is quoted with an octet count (see the description of literal in String under Data Formats). In the other case, the command arguments require server feedback (see the AUTHENTICATE command). In either case, the server sends a command continuation request response if it's ready for the octets (if appropriate) and the rest of the command. This response is prefixed with the token + ๐ฆ
Note: If instead, the server detected an error in the command, it sends a BAD completion response with a tag matching the command (as described below) to reject the command and prevent the client from sending any more of the command. It's also possible for the server to send a completion response for some other command (if multiple commands are in progress), or untagged data. In either case, the command continuation request is still pending. The client takes the appropriate action for the response, and reads another response from the server. In all cases, the client MUST send a complete command (including receiving all command continuation request responses and command continuations for the command) before initiating a new command. ๐
The protocol receiver of an IMAP4rev1 server reads a command line from the client, parses the command and its arguments, and transmits server data and a server command completion result response ๐ง
2.2.2. Server Protocol Sender and Client Protocol Receiver
Data the server sends to the client, along with status responses that don't indicate command completion, are prefixed with the token *. These are called untagged responses ๐ธ
Server data MAY be sent as a result of a client command, or MAY be sent unilaterally by the server. There's no syntactic difference between server data that resulted from a specific command and server data that was sent unilaterally ๐ซถ
The server completion result response indicates whether the operation succeeded or failed. It's tagged with the same tag as the client command that began the operation. So if more than one command is in progress, the tag in a server completion response tells you which command it applies to ๐ There are three possible server completion responses: OK (success), NO (failure), or BAD (a protocol error, like an unrecognized command or a command syntax error) โจ
Servers SHOULD enforce the syntax outlined in this specification strictly. Any client command with a protocol syntax error, including (but not limited to) missing or extraneous spaces or arguments, SHOULD be rejected, and the client given a BAD server completion response ๐
The protocol receiver of an IMAP4rev1 client reads a response line from the server. It then acts on the response based on the first token of the response, which can be a tag, a *, or a + ๐
A client MUST be prepared to accept any server response at all times ๐ฅ That includes server data that wasn't requested. Server data SHOULD be recorded, so the client can reference its recorded copy instead of sending a command to the server to request the data again. For certain server data, the data MUST be recorded ๐ญ
This topic is discussed in greater detail in the Server Responses section ๐
2.3. Message Attributes
In addition to message text, each message has several attributes associated with it ๐ฆ These attributes can be retrieved individually or together with other attributes or message texts โจ
2.3.1. Message Numbers ๐ฆ
okay so messages in IMAP4rev1 get accessed by one of two numbers: the unique identifier or the message sequence number. bestie this is the core of the whole vibe ๐
2.3.1.1. Unique Identifier (UID) Message Attribute โจ
A 32-bit value gets assigned to each message. When it's paired with the unique identifier validity value (more on that in a sec), it makes a 64-bit value that MUST NOT refer to any other message in the mailbox, or any later mailbox with the same name, forever. forever!! ๐ญ that's a whole commitment, iconic.
UIDs get assigned in a strictly ascending fashion in the mailbox. So every time a new message shows up, it gets a higher UID than the ones before it. Unlike message sequence numbers, UIDs are not necessarily contiguous ๐ธ (they can have gaps, no cap).
A message's UID MUST NOT change during the session ๐, and it SHOULD NOT change between sessions either. If the UID does change between sessions, that change MUST be detectable using the UIDVALIDITY mechanism we'll get to below. Persistent UIDs are required for a client to resynchronize its state from a previous session with the server (think disconnected or offline access clients), and [IMAP-DISC] has more on that ๐ง
Every mailbox has two values that help with UID handling: the next unique identifier value and the unique identifier validity value.
The next unique identifier value is the predicted value that will be given to a new message in the mailbox. Unless the unique identifier validity changes too (see below), the next unique identifier value MUST have the following two characteristics. First, it MUST NOT change unless new messages are added to the mailbox. Second, it MUST change whenever new messages are added to the mailbox, even if those new messages get expunged later ๐
๐ Note: The next unique identifier value is meant to help a client figure out whether any messages have been delivered to the mailbox since the last time it checked. It is NOT meant to guarantee that any message will have that exact UID. A client can only assume, at the moment it grabs the next unique identifier value, that messages arriving after that point will have a UID greater than or equal to that value.
The unique identifier validity value is sent in a UIDVALIDITY response code, inside an OK untagged response, at mailbox selection time. If UIDs from an earlier session don't persist into this session, the unique identifier validity value MUST be greater than the one used in the earlier session ๐
๐ Note: Ideally, unique identifiers SHOULD persist at all times. This spec admits that failing to persist can be unavoidable on some server setups, but it STRONGLY ENCOURAGES message store implementation techniques that avoid the problem. For example:
- Unique identifiers MUST be strictly ascending in the mailbox at all times. If the physical message store gets re-ordered by a non-IMAP agent, the UIDs in the mailbox have to be regenerated, since the old ones are no longer strictly ascending after the re-ordering.
- If the message store has no mechanism to store unique identifiers, it must regenerate them at each session, and each session must have a unique UIDVALIDITY value.
- If the mailbox is deleted and a new mailbox with the same name is created later, the server must either keep track of the unique identifiers from the previous instance of the mailbox, or assign a new UIDVALIDITY value to the new instance. A good UIDVALIDITY value to use here is a 32-bit representation of the creation date/time of the mailbox. It is alright to use a constant such as
1, but only if it is guaranteed that unique identifiers will never be reused, even when a mailbox gets deleted (or renamed) and a new mailbox by the same name is created at some future time. - The combination of mailbox name, UIDVALIDITY, and UID must refer to a single immutable message on that server forever. In particular, the internal date, [RFC-2822] size, envelope, body structure, and message texts (
RFC822,RFC822.HEADER,RFC822.TEXT, and allBODY[...]fetch data items) must never change. This does not include message numbers, nor does it include attributes that can be set by aSTOREcommand (e.g.,FLAGS) ๐ซถ
2.3.1.2. Message Sequence Number Message Attribute ๐
This one is a relative position, from 1 up to the number of messages in the mailbox. That position MUST be ordered by ascending unique identifier. Each time a new message is added, it gets a message sequence number that is 1 higher than the number of messages in the mailbox before that new message was added.
Message sequence numbers can get reassigned during the session, which is very plot twisty ๐ For example, when a message is permanently removed (expunged) from the mailbox, the message sequence number of every message after it goes down by one. The number of messages in the mailbox also goes down. Similarly, a new message can be given a message sequence number that some other message had before an expunge.
Message sequence numbers aren't only for finding messages by position, either. You can do math with them too! ๐งฎ For example, if an untagged 11 EXISTS comes in, and an untagged 8 EXISTS came in earlier, then three new messages have arrived, with message sequence numbers of 9, 10, and 11. Another example: if message 287 in a 523 message mailbox has UID 12345, then there are exactly 286 messages with lesser UIDs and 236 messages with greater UIDs. the math ate โจ
2.3.2. Flags Message Attribute ๐ณ๏ธโ๐
Flags are a list of zero or more named tokens attached to a message. Adding a flag to that list sets it, and removing it clears it. There are two types of flags in IMAP4rev1, and a flag of either type can be permanent or session-only ๐
A system flag is a flag name that is pre-defined in this spec. All system flags begin with "". Certain system flags (\Deleted and \Seen) have special semantics described elsewhere. The currently-defined system flags are:
\Seen
Message has been read
\Answered
Message has been answered
\Flagged
Message is "flagged" for urgent/special attention
\Deleted
Message is "deleted" for removal by later EXPUNGE
\Draft
Message has not completed composition (marked as a draft).
\Recent
Message is "recently" arrived in this mailbox. This session
is the first session to have been notified about this
message; if the session is read-write, subsequent sessions
will not see \Recent set for this message. This flag can not
be altered by the client.
If it is not possible to determine whether or not this
session is the first session to be notified about a message,
then that message SHOULD be considered recent.
If multiple connections have the same mailbox selected
simultaneously, it is undefined which of these connections
will see newly-arrived messages with \Recent set and which
will see it without \Recent set.
A keyword is defined by the server implementation. Keywords do not begin with "". Servers MAY permit the client to define new keywords in the mailbox (see the description of the PERMANENTFLAGS response code for more information) ๐
A flag can be permanent or session-only on a per-flag basis. Permanent flags are the ones the client can add or remove from the message flags permanently, so concurrent and later sessions will see any change to them. Changes to session flags only count inside that one session โณ
๐ Note: The\Recentsystem flag is a special case of a session flag.\Recentcan not be used as an argument in aSTOREorAPPENDcommand, so it can't be changed at all ๐
2.3.3. Internal Date Message Attribute ๐
This is the internal date and time of the message on the server. It is NOT the date and time in the [RFC-2822] header. It's a date and time that reflects when the message was received. For messages delivered via [SMTP], this SHOULD be the date and time of final delivery of the message as defined by [SMTP]. For messages delivered by the IMAP4rev1 COPY command, this SHOULD be the internal date and time of the source message. For messages delivered by the IMAP4rev1 APPEND command, this SHOULD be the date and time specified in the APPEND command description. All other cases are implementation defined ๐ง
2.3.4. [RFC-2822] Size Message Attribute ๐
This is the number of octets in the message, expressed in [RFC-2822] format ๐
2.3.5. Envelope Structure Message Attribute ๐
This is a parsed representation of the message's [RFC-2822] header. Be careful, bestie: the IMAP Envelope structure is not the same thing as an [SMTP] envelope ๐
2.3.6. Body Structure Message Attribute โจ
okay bestie, this one is the body structure attribute ๐ it's a parsed representation of the [MIME-IMB] body structure information of the message, so the server hands you the message's shape already sorted out ๐ซถ
2.4. Message Texts
ngl this is so good ๐ญ you can fetch the whole [RFC-2822] text of a message, but IMAP4rev1 also lets you grab just the pieces you want ๐ง specifically, you can get the [RFC-2822] message header, the [RFC-2822] message body, a [MIME-IMB] body part, or a [MIME-IMB] header. main character energy, just the bits you need ๐
3. State and Flow Diagram ๐ฆ
okay so once the connection between client and server is established, an IMAP4rev1 connection is in one of four states ๐ the initial state is identified in the server greeting. most commands are only valid in certain states, and it's a protocol error for the client to attempt a command while the connection is in an inappropriate state. the server will respond with a BAD or NO (depending upon server implementation) command completion result ๐
3.1. Not Authenticated State
in the not authenticated state, the client MUST supply authentication credentials before most commands will be permitted ๐ this state is entered when a connection starts, unless the connection has been pre-authenticated.
3.2. Authenticated State
in the authenticated state, the client is authenticated and MUST select a mailbox to access before commands that affect messages will be permitted โ
this state is entered when a pre-authenticated connection starts, when acceptable authentication credentials have been provided, after an error in selecting a mailbox, or after a successful CLOSE command.
3.3. Selected State
in the selected state, a mailbox has been selected to access ๐ฌ this state is entered when a mailbox has been successfully selected.
3.4. Logout State
in the logout state, the connection is being terminated ๐ this state can be entered as a result of a client request (via the LOGOUT command) or by unilateral action on the part of either the client or server.
if the client requests the logout state, the server MUST send an untagged BYE response and a tagged OK response to the LOGOUT command before the server closes the connection, and the client MUST read the tagged OK response to the LOGOUT command before the client closes the connection ๐
a server MUST NOT unilaterally close the connection without sending an untagged BYE response that contains the reason for having done so ๐ซ a client SHOULD NOT unilaterally close the connection, and instead SHOULD issue a LOGOUT command. if the server detects that the client has unilaterally closed the connection, the server MAY omit the untagged BYE response and simply close its connection ๐ซ
+----------------------+
|connection established|
+----------------------+
||
\/
+--------------------------------------+
| server greeting |
+--------------------------------------+
|| (1) || (2) || (3)
\/ || ||
+-----------------+ || ||
|Not Authenticated| || ||
+-----------------+ || ||
|| (7) || (4) || ||
|| \/ \/ ||
|| +----------------+ ||
|| | Authenticated |<=++ ||
|| +----------------+ || ||
|| || (7) || (5) || (6) ||
|| || \/ || ||
|| || +--------+ || ||
|| || |Selected|==++ ||
|| || +--------+ ||
|| || || (7) ||
\/ \/ \/ \/
+--------------------------------------+
| Logout |
+--------------------------------------+
||
\/
+-------------------------------+
|both sides close the connection|
+-------------------------------+
(1) connection without pre-authentication (OK greeting)
(2) pre-authenticated connection (PREAUTH greeting)
(3) rejected connection (BYE greeting)
(4) successful LOGIN or AUTHENTICATE command
(5) successful SELECT or EXAMINE command
(6) CLOSE command, or failed SELECT or EXAMINE command
(7) LOGOUT command, server shutdown, or connection closed
4. Data Formats ๐
okay so IMAP4rev1 uses textual commands and responses ๐ data in IMAP4rev1 can be in one of several forms: atom, number, string, parenthesized list, or NIL. a particular data item may take more than one form. for example, a data item defined as using "astring" syntax may be either an atom or a string ๐งฉ
4.1. Atom
an atom consists of one or more non-special characters โ๏ธ
4.2. Number
a number consists of one or more digit characters, and represents a numeric value ๐ข
4.3. String
a string is in one of two forms: either literal or quoted string โจ the literal form is the general form of string. the quoted string form is an alternative that avoids the overhead of processing a literal, at the cost of limitations on which characters may be used ๐
a literal is a sequence of zero or more octets (including CR and LF), prefix-quoted with an octet count in the form of an open brace ({), the number of octets, close brace (}), and CRLF. for literals transmitted from server to client, the CRLF is immediately followed by the octet data. for literals transmitted from client to server, the client MUST wait to receive a command continuation request (described later in this document) before sending the octet data (and the remainder of the command) ๐
a quoted string is a sequence of zero or more 7-bit characters, excluding CR and LF, with double quote (<">) characters at each end ๐
the empty string is represented as either "" (a quoted string with zero characters between double quotes) or as {0} followed by CRLF (a literal with an octet count of 0) ๐ซง
Note: Even if the octet count is 0, a client transmitting a literal MUST wait to receive a command continuation request.
4.3.1. 8-bit and Binary Strings
8-bit textual and binary mail is supported through the use of a [MIME-IMB] content transfer encoding ๐จ IMAP4rev1 implementations MAY transmit 8-bit or multi-octet characters in literals, but SHOULD do so only when the [CHARSET] is identified.
although a BINARY body encoding is defined, unencoded binary strings are not permitted ๐
โโ๏ธ a "binary string" is any string with NUL characters. implementations MUST encode binary data into a textual form, such as BASE64, before transmitting the data. a string with an excessive amount of CTL characters MAY also be considered to be binary ๐ค
4.4. Parenthesized List
data structures are represented as a "parenthesized list": a sequence of data items, delimited by space, and bounded at each end by parentheses ๐ธ a parenthesized list can contain other parenthesized lists, using multiple levels of parentheses to indicate nesting ๐ช
the empty list is represented as (), a parenthesized list with no members ๐ซ
4.5. NIL
the special form "NIL" represents the non-existence of a particular data item that is represented as a string or parenthesized list, as distinct from the empty string "" or the empty parenthesized list () ๐ป
Note: NIL is never used for any data item which takes the form of an atom. For example, a mailbox name of "NIL" is a mailbox named NIL as opposed to a non-existent mailbox name. This is because mailbox uses "astring" syntax, which is an atom or a string. Conversely, an addr-name of NIL is a non-existent personal name, because addr-name uses "nstring" syntax, which is NIL or a string, but never an atom.
5. Operational Considerations ๐
okay so the following rules are listed here to make sure all IMAP4rev1 implementations interoperate properly ๐ซถ
5.1. Mailbox Naming
mailbox names are 7-bit ๐ค client implementations MUST NOT attempt to create 8-bit mailbox names, and SHOULD interpret any 8-bit mailbox names returned by LIST or LSUB as UTF-8. server implementations SHOULD prohibit the creation of 8-bit mailbox names, and SHOULD NOT return 8-bit mailbox names in LIST or LSUB. see section 5.1.3 for more information on how to represent non-ASCII mailbox names ๐
Note: 8-bit mailbox names were undefined in earlier versions of this protocol. Some sites used a local 8-bit character set to represent non-ASCII mailbox names. Such usage is not interoperable, and is now formally deprecated ๐
the case-insensitive mailbox name INBOX is a special name reserved to mean "the primary mailbox for this user on this server" ๐ฅ the interpretation of all other names is implementation-dependent.
in particular, this specification takes no position on case sensitivity in non-INBOX mailbox names ๐คทโโ๏ธ some server implementations are fully case-sensitive; others preserve the case of a newly-created name but otherwise are case-insensitive; and yet others coerce names to a particular case. client implementations MUST interact with any of these. if a server implementation interprets non-INBOX mailbox names as case-insensitive, it MUST treat names using the international naming convention specially, as described in section 5.1.3 ๐
there are certain client considerations when creating a new mailbox name ๐
- Any character which is one of the atom-specials (see the Formal Syntax) will require that the mailbox name be represented as a quoted string or literal.
- CTL and other non-graphic characters are difficult to represent in a user interface and are best avoided.
- Although the list-wildcard characters (
%and*) are valid in a mailbox name, it is difficult to use such mailbox names with theLISTandLSUBcommands due to the conflict with wildcard interpretation. - Usually, a character (determined by the server implementation) is reserved to delimit levels of hierarchy.
- Two characters,
#and&, have meanings by convention, and should be avoided except when used in that convention.
5.1.1. Mailbox Hierarchy Naming
if it is desired to export hierarchical mailbox names, mailbox names MUST be left-to-right hierarchical using a single character to separate levels of hierarchy ๐ช the same hierarchy separator character is used for all levels of hierarchy within a single name.
5.1.2. Mailbox Namespace Naming Convention
by convention, the first hierarchical element of any mailbox name which begins with # identifies the "namespace" of the remainder of the name ๐๏ธ this makes it possible to tell apart different types of mailbox stores, each of which have their own namespaces โจ
For example, implementations which offer access to USENET newsgroups MAY use the#newsnamespace to partition the USENET newsgroup namespace from that of other mailboxes. Thus, the comp.mail.misc newsgroup would have a mailbox name of#news.comp.mail.misc, and the namecomp.mail.misccan refer to a different object (e.g., a user's private mailbox) ๐ฐ
5.1.3. Mailbox International Naming Convention โจ
okay so bestie, international mailbox names in IMAP4rev1 are written with a modified version of the UTF-7 encoding from [UTF-7] ๐. Modified UTF-7 may also be usable in servers that implement an earlier version of this protocol ๐ .
In modified UTF-7, printable US-ASCII characters represent themselves, except for & ๐. That means the characters with octet values 0x20-0x25 and 0x27-0x7e. The & character (0x26) is written as the two-octet sequence &- ๐.
All other characters (octet values 0x00-0x1f and 0x7f-0xff) get encoded in modified BASE64 ๐ง, with one twist from [UTF-7]: , is used instead of /. Modified BASE64 MUST NOT be used to represent any printing US-ASCII character which can represent itself.
& is how you shift into modified BASE64, and - is how you shift back to US-ASCII. There is no implicit shift from BASE64 back to US-ASCII, and null shifts (-& while in BASE64; note that &- while in US-ASCII means &) are not permitted. However, all names start in US-ASCII, and MUST end in US-ASCII. That is, a name that ends with a non-ASCII ISO-10646 character MUST end with a -).
The whole point of these tweaks is to fix the following problems with UTF-7 ๐ซถ:
- UTF-7 uses the
+character for shifting. That clashes with the common use of+in mailbox names, especially USENET newsgroup names. - UTF-7's encoding is BASE64, which uses the
/character. That clashes with/being a popular hierarchy delimiter. - UTF-7 prohibits the unencoded usage of
\. That clashes with\being a popular hierarchy delimiter. - UTF-7 prohibits the unencoded usage of
~. That clashes with~being used in some servers as a home directory indicator. - UTF-7 permits multiple alternate forms to represent the same string. In particular, printable US-ASCII characters can be represented in encoded form.
Modified UTF-7 is a convention, but it still sets some requirements on how servers handle any mailbox name with an embedded & character ๐. In particular, server implementations MUST preserve the exact form of the modified BASE64 portion of a modified UTF-7 name and treat that text as case-sensitive, even if names are otherwise case-insensitive or case-folded.
Server implementations SHOULD verify that any mailbox name with an embedded & character, used as an argument to CREATE, is in the correctly modified UTF-7 syntax, has no superfluous shifts, and has no encoding in modified BASE64 of any printing US-ASCII character which can represent itself. However, client implementations MUST NOT depend upon the server doing this, and SHOULD NOT attempt to create a mailbox name with an embedded & character unless it complies with the modified UTF-7 syntax.
Server implementations which export a mail store that does not follow the modified UTF-7 convention MUST convert to modified UTF-7 any mailbox name that contains either non-ASCII characters or the & character.
For example, here is a mailbox name which mixes English, Chinese, and Japanese text:
~peter/mail/&U,BTFw-/&ZeVnLIqe-
For example, the string &Jjo! is not a valid mailbox name because it does not contain a shift to US-ASCII before the !. The correct form is &Jjo-!. The string &U,BTFw-&ZeVnLIqe- is not permitted because it contains a superfluous shift. The correct form is &U,BTF2XlZyyKng-. ๐ง
5.2. Mailbox Size and Message Status Updates
At any time, a server can send data that the client did not request. Sometimes, that behavior is REQUIRED ๐ฅ. For example, agents other than the server MAY add messages to the mailbox (for example, new message delivery), change the flags of the messages in the mailbox (for example, simultaneous access to the same mailbox by multiple agents), or even remove messages from the mailbox. A server MUST send mailbox size updates automatically if a mailbox size change is observed during the processing of a command. A server SHOULD send message flag updates automatically, without requiring the client to request such updates explicitly.
There are special rules for server notification of a client about removed messages, so you don't get synchronization errors ๐. Check the description of the EXPUNGE response for more detail. In particular, it is NOT permitted to send an EXISTS response that would reduce the number of messages in the mailbox. Only the EXPUNGE response can do this.
No matter what a client decides about remembering data from the server, a client implementation MUST record mailbox size updates. It MUST NOT assume that any command after the initial mailbox selection will return the size of the mailbox ๐ .
5.3. Response when no Command in Progress
Server implementations are allowed to send an untagged response (except for EXPUNGE) while there is no command in progress. Server implementations that send such responses MUST deal with flow control considerations. Specifically, they MUST either (1) verify that the size of the data does not exceed the underlying transport's available window size, or (2) use non-blocking writes ๐.
5.4. Autologout Timer
If a server has an inactivity autologout timer, the duration of that timer MUST be at least 30 minutes โฐ. The receipt of ANY command from the client during that interval SHOULD suffice to reset the autologout timer.
5.5. Multiple Commands in Progress
The client MAY send another command without waiting for the completion result response of a command. This is subject to ambiguity rules (see below) and flow control constraints on the underlying data stream. Similarly, a server MAY begin processing another command before processing the current command to completion, subject to ambiguity rules. However, any command continuation request responses and command continuations MUST be negotiated before any subsequent command is initiated.
The exception is if an ambiguity would result because of a command that would affect the results of other commands. Clients MUST NOT send multiple commands without waiting if an ambiguity would result. If the server detects a possible ambiguity, it MUST execute commands to completion in the order given by the client ๐ง .
The most obvious example of ambiguity is when a command would affect the results of another command, for example, a FETCH of a message's flags and a STORE of that same message's flags.
A non-obvious ambiguity occurs with commands that permit an untagged EXPUNGE response (commands other than FETCH, STORE, and SEARCH), since an untagged EXPUNGE response can invalidate sequence numbers in a subsequent command. This is not a problem for FETCH, STORE, or SEARCH commands, because servers are prohibited from sending EXPUNGE responses while any of those commands are in progress. Therefore, if the client sends any command other than FETCH, STORE, or SEARCH, it MUST wait for the completion result response before sending a command with message sequence numbers.
Note: UID FETCH, UID STORE, and UID SEARCH are different commands from FETCH, STORE, and SEARCH. If the client sends a UID command, it must wait for a completion result response before sending a command with message sequence numbers.
For example, the following non-waiting command sequences are invalid ๐:
FETCH + NOOP + STORE
STORE + COPY + FETCH
COPY + COPY
CHECK + FETCH
The following are examples of valid non-waiting command sequences โจ:
FETCH + STORE + SEARCH + CHECK
STORE + COPY + EXPUNGE
UID SEARCH + UID SEARCH may be valid or invalid as a non-waiting command sequence, depending upon whether or not the second UID SEARCH contains message sequence numbers.
6. Client Commands ๐
IMAP4rev1 commands are described in this section. Commands are organized by the state in which the command is permitted. Commands that are permitted in multiple states are listed in the minimum permitted state. For example, commands valid in authenticated and selected state are listed in the authenticated state commands.
Command arguments, identified by "Arguments:" in the command descriptions below, are described by function, not by syntax. The precise syntax of command arguments is described in the Formal Syntax section.
Some commands cause specific server responses to be returned. These are identified by "Responses:" in the command descriptions below. See the response descriptions in the Responses section for information on these responses, and the Formal Syntax section for the precise syntax of these responses. It is possible for server data to be transmitted as a result of any command. Thus, commands that do not specifically require server data specify "no specific responses for this command" instead of "none".
The "Result:" in the command description refers to the possible tagged status responses to a command, and any special interpretation of these status responses.
The state of a connection is only changed by successful commands which are documented as changing state. A rejected command (BAD response) never changes the state of the connection or of the selected mailbox. A failed command (NO response) generally does not change the state of the connection or of the selected mailbox, with the exception of the SELECT and EXAMINE commands. ๐ฆ
6.1. Client Commands - Any State
The following commands are valid in any state: CAPABILITY, NOOP, and LOGOUT. ๐
6.1.1. CAPABILITY Command โจ
- Arguments: none
- Responses: REQUIRED untagged response: CAPABILITY
- Result:
- OK - capability completed
- BAD - command unknown or arguments invalid
okay so the CAPABILITY command is basically the client asking "hey, what can you do?" ๐ the server has to send a single untagged CAPABILITY response that includes "IMAP4rev1" in the list, and it MUST do that before the (tagged) OK response. no skipping, bestie ๐ซถ
anything starting with "AUTH=" means the server supports that specific auth mechanism, and all of those names are, by definition, part of this spec ๐ so an experimental "blurdybloop" authenticator would be "AUTH=XBLURDYBLOOP", NOT "XAUTH=BLURDYBLOOP" or "XAUTH=XBLURDYBLOOP". the way the naming is so strict ๐ญ iconic.
other capability names are for extensions, revisions, or amendments to the spec. check the CAPABILITY response docs for the deets โจ and nothing beyond the base IMAP4rev1 set gets turned on unless the client explicitly asks for it. no surprise features, periodt ๐
Client and server implementations MUST implement the STARTTLS, LOGINDISABLED, and AUTH=PLAIN (described in [IMAP-TLS]) capabilities. These are non-negotiable, no cap ๐ and you really need to read the Security Considerations section because it has the important stuff ๐
also check the section called "Client Commands - Experimental/Expansion" for how site or implementation-specific capabilities are formatted ๐ฆ
Example:
C: abcd CAPABILITY
S: * CAPABILITY IMAP4rev1 STARTTLS AUTH=GSSAPI
LOGINDISABLED
S: abcd OK CAPABILITY completed
C: efgh STARTTLS
S: efgh OK STARTLS completed
<TLS negotiation, further commands are under [TLS] layer>
C: ijkl CAPABILITY
S: * CAPABILITY IMAP4rev1 AUTH=GSSAPI AUTH=PLAIN
S: ijkl OK CAPABILITY completed
6.1.2. NOOP Command โจ
- Arguments: none
- Responses: no specific responses for this command (but see below)
- Result:
- OK - noop completed
- BAD - command unknown or arguments invalid
the NOOP command always succeeds ๐ธ and it literally does nothing. but it's secretly so useful ๐
any command can return a status update as untagged data, so NOOP can be used as a periodic poll for new messages or message status updates when things have been quiet for a while. this is the preferred method for doing this, btw ๐ it can also reset any inactivity autologout timer on the server, so it's giving "I'm still here, don't kick me out" energy โฐ
Example:
C: a002 NOOP
S: a002 OK NOOP completed
. . .
C: a047 NOOP
S: * 22 EXPUNGE
S: * 23 EXISTS
S: * 3 RECENT
S: * 14 FETCH (FLAGS (\Seen \Deleted))
S: a047 OK NOOP completed
6.1.3. LOGOUT Command โจ
- Arguments: none
- Responses: REQUIRED untagged response: BYE
- Result:
- OK - logout completed
- BAD - command unknown or arguments invalid
LOGOUT is the client saying "bye, I'm done with this connection" ๐ the server MUST send a BYE untagged response before the (tagged) OK response, and then close the network connection. bestie, that's the proper exit ๐ชโจ
Example:
C: A023 LOGOUT
S: * BYE IMAP4rev1 Server logging out
S: A023 OK LOGOUT completed
(Server and client then close the connection)
6.2. Client Commands - Not Authenticated State ๐
okay so in the not authenticated state, the AUTHENTICATE or LOGIN command is how you get authenticated and enter the authenticated state ๐ AUTHENTICATE is the general-purpose option that covers a whole bunch of auth techniques, privacy protection, and integrity checking. LOGIN, on the other hand, uses a traditional username and plaintext password pair, and it has no way of setting up privacy protection or integrity checking. so it's kinda the old-school one ๐
the STARTTLS command is another way to set up session privacy protection and integrity checking ๐ but it does NOT establish authentication or enter the authenticated state. different vibe entirely ๐
Server implementations MAY allow access to certain mailboxes without establishing authentication. This can be done with the ANONYMOUS [SASL] authenticator described in [ANONYMOUS] ๐ง there's also an older convention where you LOGIN with the userid "anonymous". in that case a password is required, although the server may choose to accept any password ๐ and whatever restrictions anonymous users get are implementation-dependent.
once you're authenticated (including as anonymous), you cannot re-enter the not authenticated state. it's a one-way door, bestie ๐ช๐
besides the universal commands (CAPABILITY, NOOP, and LOGOUT), the only commands valid in the not authenticated state are STARTTLS, AUTHENTICATE and LOGIN. and please read the Security Considerations section for the important info about these commands ๐ซถ
6.2.1. STARTTLS Command โจ
- Arguments: none
- Responses: no specific response for this command
- Result:
- OK - starttls completed, begin TLS negotiation
- BAD - command unknown or arguments invalid
so a [TLS] negotiation starts immediately after the CRLF at the end of the tagged OK response from the server ๐ once a client sends STARTTLS, it MUST NOT issue any further commands until a server response is seen and the [TLS] negotiation is complete. patience is a virtue, bestie โณ
the server stays in the non-authenticated state, even if client credentials are supplied during the [TLS] negotiation ๐ โโ๏ธ that doesn't stop an authentication mechanism like EXTERNAL (defined in [SASL]) from using the client identity determined by the [TLS] negotiation, though. so it's not a total dead end โจ
Once [TLS] has been started, the client MUST discard cached information about server capabilities and SHOULD re-issue the CAPABILITY command. This is necessary to protect against man-in-the-middle attacks that alter the capabilities list before STARTTLS. the server MAY advertise different capabilities after STARTTLS too ๐ so don't trust your old notes, babe ๐๐
Example:
C: a001 CAPABILITY
S: * CAPABILITY IMAP4rev1 STARTTLS LOGINDISABLED
S: a001 OK CAPABILITY completed
C: a002 STARTTLS
S: a002 OK Begin TLS negotiation now
<TLS negotiation, further commands are under [TLS] layer>
C: a003 CAPABILITY
S: * CAPABILITY IMAP4rev1 AUTH=PLAIN
S: a003 OK CAPABILITY completed
C: a004 LOGIN joe password
S: a004 OK LOGIN completed
6.2.2. AUTHENTICATE Command โจ
Arguments: authentication mechanism name
Responses: continuation data can be requested
Result: OK - authenticate completed, now in authenticated state NO - authenticate failure: unsupported authentication mechanism, credentials rejected BAD - command unknown or arguments invalid, authentication exchange cancelled
Okay so the AUTHENTICATE command is literally how you tell the server "hey, I want to log in with this [SASL] mechanism" ๐ ๐ซถ If the server actually supports the mechanism you asked for, it runs a whole auth exchange so it can verify and identify you. ๐ It MAY also negotiate an OPTIONAL security layer for the rest of your chat with the server ๐ฆ And if the mechanism isn't supported, the server SHOULD bounce your AUTHENTICATE command with a tagged NO response ๐ญ
The AUTHENTICATE command does not support the optional "initial response" feature of [SASL]. Section 5.1 of [SASL] specifies how to handle an authentication mechanism which uses an initial response. ๐ธ
The service name specified by this protocol's profile of [SASL] is "imap". ๐ง
The authentication protocol exchange is a back-and-forth of server challenges and client responses that depend on the mechanism you picked ๐ A server challenge is a command continuation request response with the "+" token followed by a BASE64 encoded string. ๐ The client response is a single line holding a BASE64 encoded string. ๐ If the client wants to cancel the exchange, it sends a line that is just a single "*". ๐ If the server gets that, it MUST reject the AUTHENTICATE command with a tagged BAD response. ๐
If a security layer gets negotiated through the [SASL] exchange, it takes effect immediately after the CRLF that ends the exchange for the client, and the CRLF of the tagged OK response for the server. โจ
While client and server implementations MUST implement the AUTHENTICATE command itself, they are not required to implement any authentication mechanisms other than the PLAIN mechanism described in [IMAP-TLS]. ๐ Also, an authentication mechanism is not required to support any security layers. ๐ซถ
Note: a server implementation MUST implement a configuration in which it does NOT permit any plaintext password mechanisms, unless either the STARTTLS command has been negotiated or some other mechanism that protects the session from password snooping has been provided. Server sites SHOULD NOT use any configuration which permits a plaintext password mechanism without such a protection mechanism against password snooping. Client and server implementations SHOULD implement additional [SASL] mechanisms that do not use plaintext passwords, such the GSSAPI mechanism described in [SASL] and/or the [DIGEST-MD5] mechanism. ๐ฅ Bestie, this one is serious: plaintext passwords are a snoop magnet ๐
Servers and clients can support multiple authentication mechanisms. ๐ The server SHOULD list its supported authentication mechanisms in the response to the CAPABILITY command so that the client knows which authentication mechanisms to use. ๐
A server MAY include a CAPABILITY response code in the tagged OK response of a successful AUTHENTICATE command in order to send capabilities automatically. ๐ It is unnecessary for a client to send a separate CAPABILITY command if it recognizes these automatic capabilities. This should only be done if a security layer was not negotiated by the AUTHENTICATE command, because the tagged OK response as part of an AUTHENTICATE command is not protected by encryption/integrity checking. [SASL] requires the client to re-issue a CAPABILITY command in this case. ๐
If an AUTHENTICATE command fails with a NO response, the client MAY try another authentication mechanism by issuing another AUTHENTICATE command. ๐ฆ It MAY also attempt to authenticate by using the LOGIN command (see section 6.2.3 for more detail). ๐ In other words, the client MAY request authentication types in decreasing order of preference, with the LOGIN command as a last resort. ๐ธ
The authorization identity passed from the client to the server during the authentication exchange is interpreted by the server as the user name whose privileges the client is requesting. ๐
Example: S: * OK IMAP4rev1 Server C: A001 AUTHENTICATE GSSAPI S: + C: YIIB+wYJKoZIhvcSAQICAQBuggHqMIIB5qADAgEFoQMCAQ6iBw MFACAAAACjggEmYYIBIjCCAR6gAwIBBaESGxB1Lndhc2hpbmd0 b24uZWR1oi0wK6ADAgEDoSQwIhsEaW1hcBsac2hpdmFtcy5jYW Mud2FzaGluZ3Rvbi5lZHWjgdMwgdCgAwIBAaEDAgEDooHDBIHA cS1GSa5b+fXnPZNmXB9SjL8Ollj2SKyb+3S0iXMljen/jNkpJX AleKTz6BQPzj8duz8EtoOuNfKgweViyn/9B9bccy1uuAE2HI0y C/PHXNNU9ZrBziJ8Lm0tTNc98kUpjXnHZhsMcz5Mx2GR6dGknb I0iaGcRerMUsWOuBmKKKRmVMMdR9T3EZdpqsBd7jZCNMWotjhi vd5zovQlFqQ2Wjc2+y46vKP/iXxWIuQJuDiisyXF0Y8+5GTpAL pHDc1/pIGmMIGjoAMCAQGigZsEgZg2on5mSuxoDHEA1w9bcW9n FdFxDKpdrQhVGVRDIzcCMCTzvUboqb5KjY1NJKJsfjRQiBYBdE NKfzK+g5DlV8nrw81uOcP8NOQCLR5XkoMHC0Dr/80ziQzbNqhx O6652Npft0LQwJvenwDI13YxpwOdMXzkWZN/XrEqOWp6GCgXTB vCyLWLlWnbaUkZdEYbKHBPjd8t/1x5Yg== S: + YGgGCSqGSIb3EgECAgIAb1kwV6ADAgEFoQMCAQ+iSzBJoAMC AQGiQgRAtHTEuOP2BXb9sBYFR4SJlDZxmg39IxmRBOhXRKdDA0 uHTCOT9Bq3OsUTXUlk0CsFLoa8j+gvGDlgHuqzWHPSQg== C: S: + YDMGCSqGSIb3EgECAgIBAAD/////6jcyG4GE3KkTzBeBiVHe ceP2CWY0SR0fAQAgAAQEBAQ= C: YDMGCSqGSIb3EgECAgIBAAD/////3LQBHXTpFfZgrejpLlLImP wkhbfa2QteAQAgAG1yYwE= S: A001 OK GSSAPI authentication successful
Note: The line breaks within server challenges and client responses are for editorial clarity and are not in real authenticators.
6.2.3. LOGIN Command ๐ท
Arguments: user name password
Responses: no specific responses for this command
Result: OK - login completed, now in authenticated state NO - login failure: user name or password rejected BAD - command unknown or arguments invalid
The LOGIN command identifies the client to the server and carries the plaintext password authenticating this user. ๐
A server MAY include a CAPABILITY response code in the tagged OK response to a successful LOGIN command in order to send capabilities automatically. ๐ It is unnecessary for a client to send a separate CAPABILITY command if it recognizes these automatic capabilities. ๐
Example: C: a001 LOGIN SMITH SESAME S: a001 OK LOGIN completed
Note: Use of the LOGIN command over an insecure network (such as the Internet) is a security risk, because anyone monitoring network traffic can obtain plaintext passwords. The LOGIN command SHOULD NOT be used except as a last resort, and it is recommended that client implementations have a means to disable any automatic use of the LOGIN command. ๐ญ Bestie, plaintext over the open internet is NOT it ๐จ
Unless either the STARTTLS command has been negotiated or some other mechanism that protects the session from password snooping has been provided, a server implementation MUST implement a configuration in which it advertises the LOGINDISABLED capability and does NOT permit the LOGIN command. Server sites SHOULD NOT use any configuration which permits the LOGIN command without such a protection mechanism against password snooping. A client implementation MUST NOT send a LOGIN command if the LOGINDISABLED capability is advertised. ๐ซถ
6.3. Client Commands - Authenticated State ๐ฆ
In the authenticated state, commands that manipulate mailboxes as atomic entities are permitted. Of these commands, the SELECT and EXAMINE commands will select a mailbox for access and enter the selected state. ๐
In addition to the universal commands (CAPABILITY, NOOP, and LOGOUT), the following commands are valid in the authenticated state: SELECT, EXAMINE, CREATE, DELETE, RENAME, SUBSCRIBE, UNSUBSCRIBE, LIST, LSUB, STATUS, and APPEND. ๐
6.3.1. SELECT Command โจ
Arguments: mailbox name
Responses: REQUIRED untagged responses: FLAGS, EXISTS, RECENT
REQUIRED OK untagged responses: UNSEEN, PERMANENTFLAGS,
UIDNEXT, UIDVALIDITY
Result: OK - select completed, now in selected state
NO - select failure, now in authenticated state: no
such mailbox, can't access mailbox
BAD - command unknown or arguments invalid
okay so SELECT is how you open a mailbox so you can actually get at the messages inside it ๐
Before the server says OK, it MUST send the following untagged data to the client. Lowkey important: earlier versions of this protocol only needed FLAGS, EXISTS, and RECENT, so client implementations SHOULD have default behaviour for any missing data, as discussed with each item ๐ซถ
FLAGS: the flags that are defined in the mailbox. There's more detail under the description of the FLAGS response.<n> EXISTS: how many messages are in the mailbox. More detail is under the EXISTS response.<n> RECENT: how many messages have the\Recentflag set. More detail is under the RECENT response.OK [UNSEEN <n>]: the message sequence number of the first unseen message in the mailbox. If this is missing, the client can not make any assumptions about the first unseen message, so it needs to issue a SEARCH command if it wants to find it ๐OK [PERMANENTFLAGS (<list of flags>)]: a list of message flags the client can change permanently. If this is missing, the client should assume that all flags can be changed permanently.OK [UIDNEXT <n>]: the next unique identifier value. Check section 2.3.1.1 for more info. If this is missing, the client can not make any assumptions about the next unique identifier value.OK [UIDVALIDITY <n>]: the unique identifier validity value. Also check section 2.3.1.1 for the full scoop. If this is missing, the server does not support unique identifiers.
Only one mailbox can be selected at a time in a connection. If you want to be in multiple mailboxes at once, you need multiple connections ๐ง A SELECT automatically deselects whatever is currently selected before it tries the new one. So if a mailbox is selected and a SELECT that fails gets attempted, no mailbox is selected afterwards. Main character chaos, no cap.
If the client is allowed to modify the mailbox, the server SHOULD prefix the text of the tagged OK response with the [READ-WRITE] response code โจ
If the client is not allowed to modify the mailbox but is allowed read access, the mailbox gets selected as read-only, and the server MUST prefix the text of the tagged OK response to SELECT with the [READ-ONLY] response code ๐ Read-only access through SELECT is different from the EXAMINE command, because certain read-only mailboxes MAY permit a change of permanent state on a per-user basis (as opposed to a global one). Netnews messages marked in a server-based .newsrc file are an example of per-user permanent state that can be changed even with read-only mailboxes. It's giving very specific, but iykyk ๐
Example: C: A142 SELECT INBOX
S: * 172 EXISTS
S: * 1 RECENT
S: * OK [UNSEEN 12] Message 12 is first unseen
S: * OK [UIDVALIDITY 3857529045] UIDs valid
S: * OK [UIDNEXT 4392] Predicted next UID
S: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
S: * OK [PERMANENTFLAGS (\Deleted \Seen \*)] Limited
S: A142 OK [READ-WRITE] SELECT completed
6.3.2. EXAMINE Command ๐ฆ
Arguments: mailbox name
Responses: REQUIRED untagged responses: FLAGS, EXISTS, RECENT
REQUIRED OK untagged responses: UNSEEN, PERMANENTFLAGS,
UIDNEXT, UIDVALIDITY
Result: OK - examine completed, now in selected state
NO - examine failure, now in authenticated state: no
such mailbox, can't access mailbox
BAD - command unknown or arguments invalid
EXAMINE is basically SELECT's twin ๐ฏโโ๏ธ It's identical and gives back the exact same output, except the mailbox is marked as read-only. No changes to the permanent state of the mailbox are allowed, per-user state included. Most importantly, EXAMINE MUST NOT cause messages to lose the \Recent flag. Not on my watch ๐ค
The text of the tagged OK response to the EXAMINE command MUST begin with the [READ-ONLY] response code.
Example: C: A932 EXAMINE blurdybloop
S: * 17 EXISTS
S: * 2 RECENT
S: * OK [UNSEEN 8] Message 8 is first unseen
S: * OK [UIDVALIDITY 3857529045] UIDs valid
S: * OK [UIDNEXT 4392] Predicted next UID
S: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
S: * OK [PERMANENTFLAGS ()] No permanent flags permitted
S: A932 OK [READ-ONLY] EXAMINE completed
6.3.3. CREATE Command ๐
Arguments: mailbox name
Responses: no specific responses for this command
Result: OK - create completed
NO - create failure: can't create mailbox with that name
BAD - command unknown or arguments invalid
CREATE makes a new mailbox with the name you give it ๐ธ You only get an OK back if a brand new mailbox with that name was actually created. It's an error to try to create INBOX, or a mailbox with a name that points at a mailbox that already exists (extant, as the spec says). If anything goes wrong while creating, you get a tagged NO response, bestie ๐
If the mailbox name ends with the server's hierarchy separator character (the one the server returns from a LIST command), that's the client saying "hey, I plan to make mailboxes under this name in the hierarchy." Server implementations that don't need this heads-up MUST ignore the declaration. Either way, the name that actually gets created is the one without the trailing hierarchy delimiter โจ
If the hierarchy separator shows up somewhere else in the name, the server SHOULD create any superior hierarchical names that the CREATE needs in order to finish successfully. So if you try to create foo/bar/zap on a server where / is the separator, it SHOULD create foo/ and foo/bar/ if they don't already exist. Building the whole family tree for you, we love a helpful server ๐ง
If a new mailbox is created with the same name as a mailbox that got deleted, its unique identifiers MUST be greater than any unique identifiers used by the previous incarnation of the mailbox. The only exception is when the new incarnation has a different unique identifier validity value. Check the UID command description for the deets ๐
Example: C: A003 CREATE owatagusiam/
S: A003 OK CREATE completed
C: A004 CREATE owatagusiam/blurdybloop
S: A004 OK CREATE completed
Note: whether this example makes a nested folder depends on whether/came back as the hierarchy separator from LIST. If/is the separator, you get a new level of hierarchy called "owatagusiam" with a member called "blurdybloop" inside it. If not, you get two mailboxes sitting at the same hierarchy level ๐
6.3.4. DELETE Command ๐
Arguments: mailbox name
Responses: no specific responses for this command
Result: OK - delete completed
NO - delete failure: can't delete mailbox with that name
BAD - command unknown or arguments invalid
DELETE permanently removes the mailbox with the given name, so use it with care ๐ญ You only get a tagged OK back if the mailbox really was deleted. It's an error to try to delete INBOX, or a mailbox name that doesn't exist.
DELETE MUST NOT remove inferior hierarchical names. For example, if a mailbox "foo" has an inferior "foo.bar" (assuming "." is the hierarchy delimiter), removing "foo" MUST NOT remove "foo.bar". Trying to delete a name that has inferior hierarchical names and has the \Noselect mailbox name attribute is an error. (Check the LIST response description for more on that one.)
It IS allowed to delete a name that has inferior hierarchical names as long as it doesn't have the \Noselect attribute. In that case, every message in that mailbox gets removed, and the name picks up the \Noselect mailbox name attribute ๐
The highest-used unique identifier of the deleted mailbox MUST be preserved, so a new mailbox created with the same name won't reuse the identifiers from the old one. The exception is when the new incarnation has a different unique identifier validity value. Check the UID command description for more detail ๐
Examples: C: A682 LIST "" *
S: * LIST () "/" blurdybloop
S: * LIST (\Noselect) "/" foo
S: * LIST () "/" foo/bar
S: A682 OK LIST completed
C: A683 DELETE blurdybloop
S: A683 OK DELETE completed
C: A684 DELETE foo
S: A684 NO Name "foo" has inferior hierarchical names
C: A685 DELETE foo/bar
S: A685 OK DELETE Completed
C: A686 LIST "" *
S: * LIST (\Noselect) "/" foo
S: A686 OK LIST completed
C: A687 DELETE foo
S: A687 OK DELETE Completed
C: A82 LIST "" *
S: * LIST () "." blurdybloop
S: * LIST () "." foo
S: * LIST () "." foo.bar
S: A82 OK LIST completed
C: A83 DELETE blurdybloop
S: A83 OK DELETE completed
C: A84 DELETE foo
S: A84 OK DELETE Completed
C: A85 LIST "" *
S: * LIST () "." foo.bar
S: A85 OK LIST completed
C: A86 LIST "" %
S: * LIST (\Noselect) "." foo
S: A86 OK LIST completed
6.3.5. RENAME Command ๐ โจ
Arguments: existing mailbox name
new mailbox name
Responses: no specific responses for this command
Result: OK - rename completed
NO - rename failure: can't rename mailbox with that name,
can't rename to mailbox with that name
BAD - command unknown or arguments invalid
okay so RENAME is how you change a mailbox's name ๐ You only get a tagged OK back if the mailbox actually got renamed. Trying to rename a mailbox that doesn't exist, or renaming to a name that's already taken, is an error, and any renaming error comes back as a tagged NO ๐ญ
If the name has inferior hierarchical names, then the inferior hierarchical names MUST also be renamed ๐ฅ For example, renaming foo to zap will rename foo/bar (assuming / is the hierarchy delimiter character) to zap/bar ๐ฆ
If the server's hierarchy separator character shows up in the name, the server SHOULD create any superior hierarchical names that are needed for the RENAME command to complete successfully. So basically, renaming foo/bar/zap to baz/rag/zowie on a server where / is the separator SHOULD create baz/ and baz/rag/ if they don't already exist ๐ง
The value of the highest-used unique identifier of the old mailbox name MUST be preserved, so that a new mailbox created with the same name won't reuse the identifiers of the former incarnation, UNLESS the new incarnation has a different unique identifier validity value. Check out the description of the UID command for more detail ๐
Renaming INBOX is allowed, and it has special behavior ๐ It moves all messages in INBOX into a new mailbox with the given name, leaving INBOX empty. If the server implementation supports inferior hierarchical names of INBOX, those stay unaffected by a rename of INBOX ๐ธ
Examples:
C: A682 LIST "" *
S: * LIST () "/" blurdybloop
S: * LIST (\Noselect) "/" foo
S: * LIST () "/" foo/bar
S: A682 OK LIST completed
C: A683 RENAME blurdybloop sarasoop
S: A683 OK RENAME completed
C: A684 RENAME foo zowie
S: A684 OK RENAME Completed
C: A685 LIST "" *
S: * LIST () "/" sarasoop
S: * LIST (\Noselect) "/" zowie
S: * LIST () "/" zowie/bar
S: A685 OK LIST completed
C: Z432 LIST "" *
S: * LIST () "." INBOX
S: * LIST () "." INBOX.bar
S: Z432 OK LIST completed
C: Z433 RENAME INBOX old-mail
S: Z433 OK RENAME completed
C: Z434 LIST "" *
S: * LIST () "." INBOX
S: * LIST () "." INBOX.bar
S: * LIST () "." old-mail
S: Z434 OK LIST completed
6.3.6. SUBSCRIBE Command ๐
Arguments: mailbox
Responses: no specific responses for this command
Result: OK - subscribe completed
NO - subscribe failure: can't subscribe to that name
BAD - command unknown or arguments invalid
SUBSCRIBE adds the mailbox name you give it to the server's set of "active" or "subscribed" mailboxes, the ones that come back from the LSUB command ๐ฆ You only get a tagged OK back if the subscription actually worked โจ
A server MAY check the mailbox argument to SUBSCRIBE to make sure it exists. But it MUST NOT unilaterally remove an existing mailbox name from the subscription list, even if a mailbox by that name doesn't exist anymore ๐
Note: This requirement is because a server site can choose to routinely remove a mailbox with a well-known name (e.g., "system-alerts") after its contents expire, with the intention of recreating it when new contents are appropriate. ๐
Example:
C: A002 SUBSCRIBE #news.comp.mail.mime
S: A002 OK SUBSCRIBE completed
6.3.7. UNSUBSCRIBE Command ๐
Arguments: mailbox name
Responses: no specific responses for this command
Result: OK - unsubscribe completed
NO - unsubscribe failure: can't unsubscribe that name
BAD - command unknown or arguments invalid
UNSUBSCRIBE is the flip side ๐ซถ It removes the specified mailbox name from the server's set of "active" or "subscribed" mailboxes, the ones returned by the LSUB command. You only get a tagged OK back if the unsubscription actually worked ๐
Example:
C: A002 UNSUBSCRIBE #news.comp.mail.mime
S: A002 OK UNSUBSCRIBE completed
6.3.8. LIST Command ๐ฆ
okay bestie, LIST is the command that goes "show me the mailboxes ๐." It grabs a subset of names from the full list of everything the client can see ๐ . You get zero or more untagged LIST replies back, each one carrying the name attributes, the hierarchy delimiter, and the name. Check the LIST reply description for the deets ๐ซถ.
- Arguments: reference name, and mailbox name with possible wildcards
- Responses: untagged responses:
LIST - Result:
OK - list completedNO - list failure: can't list that reference or nameBAD - command unknown or arguments invalid
LIST SHOULD be speedy โก, returning its data quickly without undue delay. It SHOULD NOT go to excess trouble to calculate the \Marked or \Unmarked status or do other extra processing. Imagine each name takes 1 second to process. A list of 1200 names would take 20 minutes!! bestie that's a whole lunch break ๐
If the reference name is an empty string (""), the mailbox name gets interpreted the same way SELECT interprets it ๐ง. The returned mailbox names MUST match the supplied mailbox name pattern ๐ฏ. A non-empty reference name is the name of a mailbox or a level of mailbox hierarchy, and it sets the context the mailbox name gets read in โจ.
An empty mailbox name ("") is a special request for the hierarchy delimiter and the root name of the name given in the reference. The root that comes back MAY be the empty string if the reference is non-rooted or is an empty string. Either way, a hierarchy delimiter (or NIL if there is no hierarchy) is always returned. This lets a client grab the delimiter, or figure out that the mailbox names are flat, even when no mailboxes by that name exist yet ๐.
The reference and mailbox name arguments get interpreted into a canonical form that represents an unambiguous left-to-right hierarchy. The returned mailbox names will be in that interpreted form ๐.
Note: The interpretation of the reference argument is implementation-defined. It depends on whether the server implementation has a concept of the "current working directory" and leading "break out characters," which override the current working directory. For example, on a server which exports a UNIX or NT filesystem, the reference argument contains the current working directory, and the mailbox name argument would contain the name as interpreted in the current working directory. If a server implementation has no concept of break out characters, the canonical form is normally the reference name appended with the mailbox name. Note that if the server implements the namespace convention (section 5.1.2), "#" is a break out character and must be treated as such. If the reference argument is not a level of mailbox hierarchy (that is, it is a \NoInferiors name), and/or the reference argument does not end with the hierarchy delimiter, it is implementation-dependent how this is interpreted. For example, a reference of "foo/bar" and mailbox name of "rag/baz" could be interpreted as "foo/bar/rag/baz", "foo/barrag/baz", or "foo/rag/baz". A client SHOULD NOT use such a reference argument except at the explicit request of the user. A hierarchical browser MUST NOT make any assumptions about server interpretation of the reference unless the reference is a level of mailbox hierarchy AND ends with the hierarchy delimiter.
Any part of the reference argument that is included in the interpreted form SHOULD prefix the interpreted form. It SHOULD also be in the same form as the reference name argument. This rule lets the client tell whether the returned mailbox name is in the context of the reference argument, or whether something about the mailbox argument overrode the reference argument ๐ต๏ธโโ๏ธ. Without this rule, the client would have to know the server's naming semantics, including which characters are "breakouts" that override a naming context ๐ฉ.
Here's how references and mailbox names might be interpreted on a UNIX-based server:
Reference Mailbox Name Interpretation
------------ ------------ --------------
~smith/Mail/ foo.* ~smith/Mail/foo.*
archive/ % archive/%
#news. comp.mail.* #news.comp.mail.*
~smith/Mail/ /usr/doc/foo /usr/doc/foo
archive/ ~fred/Mail/* ~fred/Mail/*
The first three examples show interpretations in the context of the reference argument. Notice that "~smith/Mail" SHOULD NOT be transformed into something like "/u2/users/smith/Mail", or the client would have no way to tell that the interpretation was in the context of the reference ๐.
The character "" is a wildcard that matches zero or more characters at its position. The character "%" is similar to "", but it does not match a hierarchy delimiter. If the "%" wildcard is the last character of a mailbox name argument, matching levels of hierarchy are also returned. If those levels aren't also selectable mailboxes, they come back with the \Noselect mailbox name attribute (see the LIST response description for more details) ๐ธ.
Server implementations are permitted to "hide" otherwise accessible mailboxes from the wildcard characters, by preventing certain characters or names from matching a wildcard in certain situations. For example, a UNIX-based server might restrict the interpretation of "*" so that an initial "/" character does not match ๐.
The special name INBOX is included in the output from LIST, if INBOX is supported by this server for this user, and if the uppercase string "INBOX" matches the interpreted reference and mailbox name arguments with wildcards as described above. The criteria for omitting INBOX is whether SELECT INBOX will return failure. Whether the user's real INBOX lives on this server or some other one doesn't matter ๐ฅ.
Example:
C: A101 LIST "" ""
S: * LIST (\Noselect) "/" ""
S: A101 OK LIST Completed
C: A102 LIST #news.comp.mail.misc ""
S: * LIST (\Noselect) "." #news.
S: A102 OK LIST Completed
C: A103 LIST /usr/staff/jones ""
S: * LIST (\Noselect) "/" /
S: A103 OK LIST Completed
C: A202 LIST ~/Mail/ %
S: * LIST (\Noselect) "/" ~/Mail/foo
S: * LIST () "/" ~/Mail/meetings
S: A202 OK LIST completed
6.3.9. LSUB Command ๐
- Arguments: reference name, and mailbox name with possible wildcards
- Responses: untagged responses:
LSUB - Result:
OK - lsub completedNO - lsub failure: can't list that reference or nameBAD - command unknown or arguments invalid
LSUB returns a subset of names from the set of names the user has declared as "active" or "subscribed" ๐. Zero or more untagged LSUB replies come back. The arguments to LSUB are in the same form as those for LIST.
The returned untagged LSUB response MAY contain different mailbox flags from a LIST untagged response. If that happens, the flags in the untagged LIST are considered more authoritative ๐.
There's a special situation when you use LSUB with the % wildcard ๐ง. Say "foo/bar" (with a hierarchy delimiter of "/") is subscribed, but "foo" is not. A "%" wildcard to LSUB must return foo, not foo/bar, in the LSUB response, and it MUST be flagged with the \Noselect attribute.
The server MUST NOT unilaterally remove an existing mailbox name from the subscription list, even if a mailbox by that name no longer exists ๐ซถ.
Example:
C: A002 LSUB "#news." "comp.mail.*"
S: * LSUB () "." #news.comp.mail.mime
S: * LSUB () "." #news.comp.mail.misc
S: A002 OK LSUB completed
C: A003 LSUB "#news." "comp.%"
S: * LSUB (\NoSelect) "." #news.comp.mail
S: A003 OK LSUB completed
6.3.10. STATUS Command โจ
- Arguments: mailbox name, and status data item names
- Responses: untagged responses:
STATUS - Result:
OK - status completedNO - status failure: no status for that nameBAD - command unknown or arguments invalid
STATUS requests the status of the mailbox you name ๐. It does not change the currently selected mailbox, and it doesn't affect the state of any messages in the queried mailbox. In particular, STATUS MUST NOT cause messages to lose the \Recent flag.
STATUS is an alternative to opening a second IMAP4rev1 connection and doing an EXAMINE on a mailbox just to check its status, without deselecting the current mailbox in your first connection ๐งโโ๏ธ.
Unlike LIST, STATUS is not guaranteed to be fast. In some circumstances it can be quite slow ๐ข. In some implementations, the server is obliged to open the mailbox read-only internally to get certain status information. Also unlike LIST, STATUS does not accept wildcards.
Note: The STATUS command is intended to access the status of mailboxes other than the currently selected mailbox. Because the STATUS command can cause the mailbox to be opened internally, and because this information is available by other means on the selected mailbox, the STATUS command SHOULD NOT be used on the currently selected mailbox. The STATUS command MUST NOT be used as a "check for new messages in the selected mailbox" operation (refer to sections 7, 7.3.1, and 7.3.2 for more information about the proper method for new message checking). Because the STATUS command is not guaranteed to be fast in its results, clients SHOULD NOT expect to be able to issue many consecutive STATUS commands and obtain reasonable performance.
The currently defined status data items you can request are:
MESSAGES- The number of messages in the mailbox.RECENT- The number of messages with the\Recentflag set.UIDNEXT- The next unique identifier value of the mailbox. Refer to section 2.3.1.1 for more information.UIDVALIDITY- The unique identifier validity value of the mailbox. Refer to section 2.3.1.1 for more information.UNSEEN- The number of messages which do not have the\Seenflag set.
Example:
C: A042 STATUS blurdybloop (UIDNEXT MESSAGES)
S: * STATUS blurdybloop (MESSAGES 231 UIDNEXT 44292)
S: A042 OK STATUS completed
6.3.11. APPEND Command ๐ฌ
Arguments: mailbox name
OPTIONAL flag parenthesized list
OPTIONAL date/time string
message literal
Responses: no specific responses for this command
Result: OK - append completed
NO - append error: can't append to that mailbox, error
in flags or date/time or message text
BAD - command unknown or arguments invalid
okay so APPEND adds your literal argument as a brand new message at the very end of the destination mailbox ๐ this argument SHOULD be shaped like an [RFC-2822] message, and 8-bit characters are totally allowed in there ๐ if your server can't keep 8-bit data intact, it MUST be able to reversibly convert that 8-bit APPEND data to 7-bit using a [MIME-IMB] content transfer encoding. no cap, that's the safety net ๐ซถ
Note: There MAY be exceptions, e.g., draft messages, in which required [RFC-2822] header lines are omitted in the message literal argument to APPEND. The full implications of doing so MUST be understood and carefully weighed. ๐
if you pass a flag parenthesized list, those flags SHOULD get set on the new message ๐ณ๏ธโ๐ if you don't, the flag list defaults to empty. either way, the Recent flag gets set too โจ
same energy for dates: if you give a date-time, the internal date SHOULD be set to it. if you don't, it defaults to the current date and time ๐ฐ๏ธ
now the drama ๐ญ if the append fails for ANY reason, the mailbox MUST be restored to exactly how it was before the APPEND attempt. no partial appending is permitted. it's all or nothing, bestie ๐
if the destination mailbox doesn't exist, the server MUST return an error and MUST NOT automatically create the mailbox ๐ โโ๏ธ unless it's certain the mailbox can't be created, the server MUST send the response code "[TRYCREATE]" as the prefix of the text of the tagged NO response. this is basically the server whispering "hey, try a CREATE and then retry your APPEND if that works" ๐ง
if the mailbox is currently selected, the normal new message actions SHOULD occur. specifically, the server SHOULD notify the client immediately with an untagged EXISTS response. if the server doesn't do that, the client MAY issue a NOOP command (or failing that, a CHECK command) after one or more APPEND commands ๐ฆ
Example:
C: A003 APPEND saved-messages (\Seen) {310}
S: + Ready for literal data
C: Date: Mon, 7 Feb 1994 21:52:25 -0800 (PST)
C: From: Fred Foobar <foobar@Blurdybloop.COM>
C: Subject: afternoon meeting
C: To: mooch@owatagu.siam.edu
C: Message-Id: <B27397-0100000@Blurdybloop.COM>
C: MIME-Version: 1.0
C: Content-Type: TEXT/PLAIN; CHARSET=US-ASCII
C:
C: Hello Joe, do you think we can meet at 3:30 tomorrow?
C:
S: A003 OK APPEND completed
Note: The APPEND command is not used for message delivery, because it does not provide a mechanism to transfer [SMTP] envelope information. ๐ญ so don't go using APPEND as your mail delivery service, babe ๐
6.4. Client Commands - Selected State ๐
in the selected state, commands that manipulate messages in a mailbox are permitted ๐
on top of the universal commands (CAPABILITY, NOOP, and LOGOUT) and the authenticated state commands (SELECT, EXAMINE, CREATE, DELETE, RENAME, SUBSCRIBE, UNSUBSCRIBE, LIST, LSUB, STATUS, and APPEND), the following commands are valid in the selected state: CHECK, CLOSE, EXPUNGE, SEARCH, FETCH, STORE, COPY, and UID ๐
6.4.1. CHECK Command ๐
Arguments: none
Responses: no specific responses for this command
Result: OK - check completed BAD - command unknown or arguments invalid
the CHECK command requests a checkpoint of the currently selected mailbox โ
a checkpoint is any implementation-dependent housekeeping tied to the mailbox (like syncing the server's in-memory state of the mailbox with what's on its disk) that doesn't normally happen as part of every command ๐งน a checkpoint MAY take a non-instantaneous amount of real time to complete, so be patient, it's giving slow-cooked ๐ฒ and if a server has no housekeeping to do, CHECK is equivalent to NOOP ๐
there is no guarantee that an EXISTS untagged response will happen as a result of CHECK ๐ NOOP, not CHECK, SHOULD be used for new message polling. main character rule, honestly ๐
Example:
C: FXXZ CHECK
S: FXXZ OK CHECK Completed
6.4.2. CLOSE Command ๐ช
Arguments: none
Responses: no specific responses for this command
Result: OK - close completed, now in authenticated state BAD - command unknown or arguments invalid
the CLOSE command permanently removes all messages that have the \Deleted flag set from the currently selected mailbox, and it takes you from the selected state back to the authenticated state ๐ฆ no untagged EXPUNGE responses get sent, so it's way quieter ๐คซ
nothing gets removed and no error is given if the mailbox was selected by an EXAMINE command or is otherwise selected read-only ๐ซถ
even if a mailbox is selected, a SELECT, EXAMINE, or LOGOUT command MAY be issued without previously issuing a CLOSE command ๐ธ those three implicitly close the currently selected mailbox without doing an expunge. BUT, when lots of messages are deleted, a CLOSE-LOGOUT or CLOSE-SELECT sequence is considerably faster than an EXPUNGE-LOGOUT or EXPUNGE-SELECT, because no untagged EXPUNGE responses (which the client would probably ignore anyway) get sent ๐ speedy and iconic โจ
Example:
C: A341 CLOSE
S: A341 OK CLOSE completed
6.4.3. EXPUNGE Command ๐๏ธ
Arguments: none
Responses: untagged responses: EXPUNGE
Result: OK - expunge completed NO - expunge failure: can't expunge (e.g., permission denied) BAD - command unknown or arguments invalid
the EXPUNGE command permanently removes all messages that have the \Deleted flag set from the currently selected mailbox ๐ฅ before the server returns an OK to the client, it sends an untagged EXPUNGE response for each message that gets removed ๐ฃ that's the receipt, no cap ๐งพ
Example:
C: A202 EXPUNGE
S: * 3 EXPUNGE
S: * 3 EXPUNGE
S: * 5 EXPUNGE
S: * 8 EXPUNGE
S: A202 OK EXPUNGE completed
Note: In this example, messages 3, 4, 7, and 11 had the\Deletedflag set. See the description of the EXPUNGE response for further explanation. ๐ the numbers shift as each message disappears, which is why the same3shows up twice. wild, right? ๐ง
6.4.4. SEARCH Command โจ
Okay bestie, the SEARCH command is how you dig through a mailbox for the messages that match your vibe ๐๐ Here's the setup:
Arguments: OPTIONAL [CHARSET] specification
searching criteria (one or more)
Responses: REQUIRED untagged response: SEARCH
Result: OK - search completed
NO - search error: can't search that [CHARSET] or
criteria
BAD - command unknown or arguments invalid
So the SEARCH command looks through the mailbox for messages that match your searching criteria ๐ง The criteria are made of one or more search keys, and the server replies with an untagged SEARCH response listing the message sequence numbers of everything that matched. Main character energy ๐
When you stack multiple keys, the result is the intersection (AND function) of all the matches, so every key has to be true at once ๐ Like, DELETED FROM "SMITH" SINCE 1-Feb-1994 gets you all the deleted messages from Smith that landed in the mailbox on or after February 1, 1994. And you can also wrap a parenthesized list of keys inside another key, which is how you use things like OR and NOT ๐ฆ
Okay, one lowkey detail: server implementations MAY exclude [MIME-IMB] body parts with terminal content media types other than TEXT and MESSAGE from consideration in SEARCH matching ๐ธ So the server is allowed to skip those parts when it's searching.
Now the CHARSET part ๐ซถ The OPTIONAL [CHARSET] specification is just the word CHARSET followed by a registered [CHARSET], and it tells the server what character set the strings in your criteria are written in. Any [MIME-IMB] content transfer encodings, plus [MIME-HDRS] strings in [RFC-2822]/[MIME-IMB] headers, MUST be decoded before comparing text in a [CHARSET] other than US-ASCII. Real talk: US-ASCII MUST be supported, and other [CHARSET]s MAY be supported ๐
If the server doesn't support the CHARSET you asked for, it MUST return a tagged NO response (not a BAD) ๐ That response SHOULD contain the BADCHARSET response code, and that code MAY list the [CHARSET]s the server does support ๐
Also, for every search key that uses strings, a message matches if the string is a substring of the field, and the matching is case-insensitive โจ So "smith" finds "SMITH" ๐
Here are the defined search keys. Check the Formal Syntax section for the exact syntax of the arguments ๐
<sequence set>: Messages whose message sequence numbers are in the specified message sequence number set.ALL: All messages in the mailbox. This is the default initial key for ANDing.ANSWERED: Messages with the\Answeredflag set.BCC <string>: Messages that contain the specified string in the envelope structure's BCC field.BEFORE <date>: Messages whose internal date (ignoring time and timezone) is earlier than the specified date.BODY <string>: Messages that contain the specified string in the body of the message.CC <string>: Messages that contain the specified string in the envelope structure's CC field.DELETED: Messages with the\Deletedflag set.DRAFT: Messages with the\Draftflag set.FLAGGED: Messages with the\Flaggedflag set.FROM <string>: Messages that contain the specified string in the envelope structure's FROM field.HEADER <field-name> <string>: Messages that have a header with the specified field-name (as defined in [RFC-2822]) and that contain the specified string in the text of the header (what comes after the colon). If the string is zero-length, this matches all messages that have a header line with the specified field-name, no matter what the contents are. ๐KEYWORD <flag>: Messages with the specified keyword flag set.LARGER <n>: Messages with an [RFC-2822] size larger than the specified number of octets.NEW: Messages that have the\Recentflag set but not the\Seenflag. This is functionally equivalent to(RECENT UNSEEN). ๐ธNOT <search-key>: Messages that do not match the specified search key.OLD: Messages that do not have the\Recentflag set. This is functionally equivalent toNOT RECENT(as opposed toNOT NEW).ON <date>: Messages whose internal date (ignoring time and timezone) is within the specified date.OR <search-key1> <search-key2>: Messages that match either search key.RECENT: Messages that have the\Recentflag set.SEEN: Messages that have the\Seenflag set.SENTBEFORE <date>: Messages whose [RFC-2822] Date: header (ignoring time and timezone) is earlier than the specified date.SENTON <date>: Messages whose [RFC-2822] Date: header (ignoring time and timezone) is within the specified date.SENTSINCE <date>: Messages whose [RFC-2822] Date: header (ignoring time and timezone) is within or later than the specified date.SINCE <date>: Messages whose internal date (ignoring time and timezone) is within or later than the specified date.SMALLER <n>: Messages with an [RFC-2822] size smaller than the specified number of octets.SUBJECT <string>: Messages that contain the specified string in the envelope structure's SUBJECT field.TEXT <string>: Messages that contain the specified string in the header or body of the message.TO <string>: Messages that contain the specified string in the envelope structure's TO field.UID <sequence set>: Messages with unique identifiers in the specified unique identifier set. Sequence set ranges are permitted. ๐ฆUNANSWERED: Messages that do not have the\Answeredflag set.UNDELETED: Messages that do not have the\Deletedflag set.UNDRAFT: Messages that do not have the\Draftflag set.UNFLAGGED: Messages that do not have the\Flaggedflag set.UNKEYWORD <flag>: Messages that do not have the specified keyword flag set.UNSEEN: Messages that do not have the\Seenflag set.
Here's what it looks like in action ๐
C: A282 SEARCH FLAGGED SINCE 1-Feb-1994 NOT FROM "Smith"
S: * SEARCH 2 84 882
S: A282 OK SEARCH completed
C: A283 SEARCH TEXT "string not in mailbox"
S: * SEARCH
S: A283 OK SEARCH completed
C: A284 SEARCH CHARSET UTF-8 TEXT {6}
C: XXXXXX
S: * SEARCH 43
S: A284 OK SEARCH completed
Note: since this document is restricted to 7-bit ASCII text, it's not possible to show actual UTF-8 data ๐ The XXXXXX is just a placeholder for what would be 6 octets of 8-bit data in a real transaction.
6.4.5. FETCH Command โจ
Arguments: sequence set, message data item names or macro
Responses: untagged responses: FETCH
Result:
- OK - fetch completed
- NO - fetch error: can't fetch that data
- BAD - command unknown or arguments invalid
okay so FETCH is the command that pulls data about messages out of the mailbox ๐ฌ๐ซถ You can grab a single atom or a whole parenthesized list of data items, bestie.
Most data items, the ones under the msg-att-static rule in the formal syntax, are static and MUST NOT change for any particular message ๐ Then there are the msg-att-dynamic ones, which MAY change, either because a STORE command changed them or because of outside events ๐ฆ
For example, if a client gets an ENVELOPE for a message it already knows the envelope for, it can safely ignore the newly sent envelope. ๐
There are three macros that bundle up commonly used sets of data items. They're handy shortcuts, but a macro must be used by itself, not mixed in with other macros or data items ๐
ALL Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE)
FAST Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE)
FULL Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY)
These are the data items you can currently fetch ๐
BODY Non-extensible form of BODYSTRUCTURE. ๐ง
BODY[<section>]<<partial>> This gives you the text of one particular body section. The section specification is a set of zero or more part specifiers, separated by periods. A part specifier is either a part number or one of these: HEADER, HEADER.FIELDS, HEADER.FIELDS.NOT, MIME, or TEXT. An empty section specification refers to the entire message, header included ๐
Every message has at least one part number. Non-[MIME-IMB] messages, and non-multipart [MIME-IMB] messages with no encapsulated message, only have a part 1 ๐ธ
Multipart messages get consecutive part numbers, in the order they show up in the message. If a particular part is of type message or multipart, its parts MUST be indicated by a period followed by the part number within that nested multipart part. Iconic nesting energy ๐ช
A part of type MESSAGE/RFC822 also has nested part numbers, which refer to parts of the MESSAGE part's body.
The HEADER, HEADER.FIELDS, HEADER.FIELDS.NOT, and TEXT part specifiers can be the sole part specifier, or they can be prefixed by one or more numeric part specifiers, as long as the numeric part specifier refers to a part of type MESSAGE/RFC822. The MIME part specifier MUST be prefixed by one or more numeric part specifiers ๐
The HEADER, HEADER.FIELDS, and HEADER.FIELDS.NOT part specifiers refer to the [RFC-2822] header of the message, or of an encapsulated [MIME-IMT] MESSAGE/RFC822 message. HEADER.FIELDS and HEADER.FIELDS.NOT are followed by a list of field-name names (as defined in [RFC-2822]) and return a subset of the header. The subset from HEADER.FIELDS only has the header fields whose field-name matches one of the names in the list. The subset from HEADER.FIELDS.NOT is the opposite: only the header fields with a non-matching field-name. Field matching is case-insensitive but otherwise exact ๐ Subsetting does not exclude the [RFC-2822] delimiting blank line between the header and the body. The blank line is included in all header fetches, except for a message that has no body and no blank line โจ
The MIME part specifier refers to the [MIME-IMB] header for this part ๐
The TEXT part specifier refers to the text body of the message, leaving out the [RFC-2822] header ๐ฆ
Here's an example of a complex message with some of its part specifiers: ๐ง
HEADER ([RFC-2822] header of the message)
TEXT ([RFC-2822] text body of the message) MULTIPART/MIXED
1 TEXT/PLAIN
2 APPLICATION/OCTET-STREAM
3 MESSAGE/RFC822
3.HEADER ([RFC-2822] header of the message)
3.TEXT ([RFC-2822] text body of the message) MULTIPART/MIXED
3.1 TEXT/PLAIN
3.2 APPLICATION/OCTET-STREAM
4 MULTIPART/MIXED
4.1 IMAGE/GIF
4.1.MIME ([MIME-IMB] header for the IMAGE/GIF)
4.2 MESSAGE/RFC822
4.2.HEADER ([RFC-2822] header of the message)
4.2.TEXT ([RFC-2822] text body of the message) MULTIPART/MIXED
4.2.1 TEXT/PLAIN
4.2.2 MULTIPART/ALTERNATIVE
4.2.2.1 TEXT/PLAIN
4.2.2.2 TEXT/RICHTEXT
You can also fetch a substring of the designated text ๐ Do this by adding an open angle bracket (<), the octet position of the first desired octet, a period, the maximum number of octets you want, and a close angle bracket (>) to the part specifier. If the starting octet is past the end of the text, you get an empty string back ๐ซง
Any partial fetch that tries to read past the end of the text gets truncated as needed. A partial fetch that starts at octet 0 comes back as a partial fetch, even if that truncation happened ๐
Note: This means thatBODY[]<0.2048>of a 1500-octet message will returnBODY[]<0>with a literal of size 1500, notBODY[]. Plot twist, iykyk ๐ญ
Note: A substring fetch of aHEADER.FIELDSorHEADER.FIELDS.NOTpart specifier is calculated after subsetting the header. โจ
The \Seen flag is implicitly set. If that makes the flags change, they SHOULD be included as part of the FETCH responses ๐
BODY.PEEK[<section>]<<partial>> An alternate form of BODY[<section>] that does NOT implicitly set the \Seen flag. Sneaky, but make it make sense ๐ต๏ธโโ๏ธ (Note the spec only says it does not implicitly set \Seen, so that's all we're claiming, bestie.)
BODYSTRUCTURE The [MIME-IMB] body structure of the message. The server computes this by parsing the [MIME-IMB] header fields in the [RFC-2822] header and the [MIME-IMB] headers ๐
ENVELOPE The envelope structure of the message. The server computes this by parsing the [RFC-2822] header into its component parts, defaulting various fields as necessary ๐
FLAGS The flags that are set for this message. ๐ฉ
INTERNALDATE The internal date of the message. ๐๏ธ
RFC822 Functionally equivalent to BODY[], but the syntax of the resulting untagged FETCH data is different (RFC822 is returned) ๐
RFC822.HEADER Functionally equivalent to BODY.PEEK[HEADER], but the syntax of the resulting untagged FETCH data is different (RFC822.HEADER is returned) ๐ท
RFC822.SIZE The [RFC-2822] size of the message. ๐
RFC822.TEXT Functionally equivalent to BODY[TEXT], but the syntax of the resulting untagged FETCH data is different (RFC822.TEXT is returned) ๐ซ
UID The unique identifier for the message. ๐
Example:
C: A654 FETCH 2:4 (FLAGS BODY[HEADER.FIELDS (DATE FROM)])
S: * 2 FETCH ....
S: * 3 FETCH ....
S: * 4 FETCH ....
S: A654 OK FETCH completed
6.4.6. STORE Command โจ
Arguments: sequence set, message data item name, value for message data item
Responses: untagged responses: FETCH
Result:
- OK - store completed
- NO - store error: can't store that data
- BAD - command unknown or arguments invalid
okay so STORE is the command that changes data attached to messages in the mailbox ๐ ๏ธ๐ Normally it hands back the updated value in an untagged FETCH response. Add a .SILENT suffix to the data item name and the untagged FETCH is skipped. The server SHOULD assume the client already worked out the updated value itself, or doesn't care about it ๐คซ
Note: Whether or not .SILENT was used, the server SHOULD send an untagged FETCH response if a change to a message's flags from an external source is observed. The whole point is that the status of the flags is determinate without a race condition ๐
These are the data items you can currently store ๐
FLAGS <flag list> Replace the flags for the message (other than \Recent) with the argument. The new value of the flags is returned as if a FETCH of those flags was done. ๐
FLAGS.SILENT <flag list> Equivalent to FLAGS, but without returning a new value. ๐ค
+FLAGS <flag list> Add the argument to the flags for the message. The new value of the flags is returned as if a FETCH of those flags was done. โ
+FLAGS.SILENT <flag list> Equivalent to +FLAGS, but without returning a new value. โ๐ค
-FLAGS <flag list> Remove the argument from the flags for the message. The new value of the flags is returned as if a FETCH of those flags was done. โ
-FLAGS.SILENT <flag list> Equivalent to -FLAGS, but without returning a new value. โ๐ค
Example:
C: A003 STORE 2:4 +FLAGS (\Deleted)
S: * 2 FETCH (FLAGS (\Deleted \Seen))
S: * 3 FETCH (FLAGS (\Deleted))
S: * 4 FETCH (FLAGS (\Deleted \Flagged \Seen))
S: A003 OK STORE completed
6.4.7. COPY Command โจ
Arguments: sequence set, mailbox name
Responses: no specific responses for this command
Result:
- OK - copy completed
- NO - copy error: can't copy those messages or to that name
- BAD - command unknown or arguments invalid
okay so COPY dupes the specified message(s) onto the end of the destination mailbox ๐ ๐ The flags and internal date of the message(s) SHOULD be preserved, and the Recent flag SHOULD be set, in the copy ๐ธ
If the destination mailbox doesn't exist, a server SHOULD return an error. It SHOULD NOT automatically create the mailbox ๐ โโ๏ธ Unless it's certain that the destination mailbox can not be created, the server MUST send the response code "[TRYCREATE]" as the prefix of the text of the tagged NO response. This is a little hint for the client that it can try a CREATE command and retry the COPY if the CREATE works ๐ง
Warning: If the COPY command is unsuccessful for any reason, server implementations MUST restore the destination mailbox to its state before the COPY attempt. No messy leftovers, periodt ๐
Example:
C: A003 COPY 2:4 MEETING
S: A003 OK COPY completed
6.4.8. UID Command โจ
- Arguments: command name, command arguments
- Responses: untagged responses:
FETCH,SEARCH - Result:
- OK - UID command completed
- NO - UID command error
- BAD - command unknown or arguments invalid
okay so the UID command comes in two forms ๐ bestie, let's go.
In the first form, you give it a COPY, FETCH, or STORE command with the arguments that command normally takes. The catch is that the numbers in the sequence set are unique identifiers instead of message sequence numbers ๐ฆ. Sequence set ranges are permitted, but don't assume UIDs are contiguous, because they might have gaps ๐
A non-existent unique identifier just gets ignored, no error message at all ๐. So a UID FETCH can come back with an OK and zero data, or a UID COPY or UID STORE can say OK and not actually do anything. Lowkey wild, but that's the vibe.
In the second form, the UID command wraps a SEARCH command with SEARCH arguments ๐. The arguments are interpreted the same way as regular SEARCH, but the numbers in the SEARCH response are unique identifiers instead of message sequence numbers. For example, UID SEARCH 1:100 UID 443:557 gives you the unique identifiers in the intersection of two sequence sets: the message sequence number range 1:100 and the UID range 443:557. Iconic intersection energy ๐ธ
Note: in that example, the UID range 443:557 shows up. The same comment about non-existent unique identifiers being ignored without any error message also applies here. So even if neither UID 443 nor 557 exists, that range is still valid and would include an existing UID 495 โจ
Also, a UID range of 559:* always includes the UID of the last message in the mailbox, even if 559 is higher than any assigned UID value ๐. That's because the contents of a range don't depend on the order of its endpoints. So any UID range with * as one of the endpoints indicates at least one message (the one with the highest numbered UID), unless the mailbox is empty.
The number after the * in an untagged FETCH response is always a message sequence number, not a unique identifier, even for a UID command response ๐ But here's the plot twist: server implementations MUST implicitly include the UID message data item as part of any FETCH response caused by a UID command, whether or not you asked for UID as a message data item in the FETCH. Main character behaviour from the server side ๐
Note: the rule about including the UID message data item in a FETCH response mostly matters for UID FETCH and UID STORE, including a UID FETCH that doesn't list UID as a message data item. It's unlikely that the other UID commands will cause an untagged FETCH, but the rule applies to them too ๐ซถ
Example:
C: A999 UID FETCH 4827313:4828442 FLAGS
S: * 23 FETCH (FLAGS (\Seen) UID 4827313)
S: * 24 FETCH (FLAGS (\Seen) UID 4827943)
S: * 25 FETCH (FLAGS (\Seen) UID 4828442)
S: A999 OK UID FETCH completed
6.5. Client Commands - Experimental/Expansion ๐งช
6.5.1. X<atom> Command ๐
- Arguments: implementation defined
- Responses: implementation defined
- Result:
- OK - command completed
- NO - failure
- BAD - command unknown or arguments invalid
anything starting with an X is an experimental command ๐งช Any command that isn't part of this specification, isn't in a standard or standards-track revision of it, and isn't an IESG-approved experimental protocol, MUST use the X prefix. Experimental untagged responses MUST also be prefixed with an X too. And servers MUST NOT send those untagged responses unless the client asked for them by issuing the matching experimental command. No surprise pop-ups for you, bestie ๐ โโ๏ธ
Example:
C: a441 CAPABILITY
S: * CAPABILITY IMAP4rev1 XPIG-LATIN
S: a441 OK CAPABILITY completed
C: A442 XPIG-LATIN
S: * XPIG-LATIN ow-nay eaking-spay ig-pay atin-lay
S: A442 OK XPIG-LATIN ompleted-cay
7. Server Responses ๐จ
Server responses come in three forms: status responses, server data, and command continuation requests ๐ The information in a server response, marked "Contents:" in the descriptions below, is described by function, not by syntax. The exact syntax lives in the Formal Syntax section, so go there if you want the nitty-gritty ๐ค
The client MUST be prepared to accept any response at all times. Literally any response, any time ๐ญ
Status responses can be tagged or untagged. Tagged ones show the completion result (OK, NO, or BAD) of a client command, and they carry a tag matching that command ๐ท๏ธ
Some status responses, and all server data, are untagged. An untagged response is marked with the token * instead of a tag. Untagged status responses are for the server greeting, or for server status that doesn't mean a command finished (like an impending system shutdown alert) โ ๏ธ Historically, untagged server data is called "unsolicited data", but strictly speaking only unilateral server data is truly "unsolicited" ๐
Certain server data MUST be recorded by the client when it arrives. The description of that data says so. This is critical info that changes how all later commands and responses get interpreted, like updates about messages being created or destroyed ๐งจ
Other server data SHOULD be recorded for later reference. If the client doesn't need to record the data, or recording it has no obvious purpose (for example, a SEARCH response when no SEARCH command is in progress), the data SHOULD be ignored ๐๏ธ
An example of unilateral untagged server data happens when the IMAP connection is in the selected state ๐ In that state, the server checks the mailbox for new messages as part of command execution. Normally that happens with every command, so a NOOP command is enough to check for new messages. If new messages turn up, the server sends untagged EXISTS and RECENT responses reflecting the new size of the mailbox ๐ฌ Server implementations that offer multiple simultaneous access to the same mailbox SHOULD also send appropriate unilateral untagged FETCH and EXPUNGE responses if another agent changes the flags on any message or expunges any messages ๐งน
Command continuation request responses use the token + instead of a tag. The server sends these to say it accepted an incomplete client command and is ready for the rest of it โ๏ธ
7.1. Server Responses - Status Responses ๐ฆ
Status responses are OK, NO, BAD, PREAUTH and BYE. OK, NO, and BAD can be tagged or untagged. PREAUTH and BYE are always untagged ๐
Status responses MAY include an OPTIONAL "response code". A response code is data inside square brackets, in the form of an atom, possibly followed by a space and arguments ๐ It holds extra info or status codes for client software beyond the OK/NO/BAD condition, and it's defined when there's a specific action a client can take based on that extra info ๐ง
The currently defined response codes are:
ALERT- The human-readable text contains a special alert that MUST be presented to the user in a fashion that calls the user's attention to the message ๐จ
BADCHARSET- Optionally followed by a parenthesized list of charsets. A SEARCH failed because the given charset is not supported by this implementation. If the optional list of charsets is given, this lists the charsets that are supported by this implementation ๐ค
CAPABILITY- Followed by a list of capabilities. This can appear in the initial OK or PREAUTH response to transmit an initial capabilities list. That makes it unnecessary for a client to send a separate CAPABILITY command if it recognizes this response ๐ง
PARSE- The human-readable text represents an error in parsing the [RFC-2822] header or [MIME-IMB] headers of a message in the mailbox ๐งฉ
PERMANENTFLAGS- Followed by a parenthesized list of flags. It indicates which of the known flags the client can change permanently. Any flags in the FLAGS untagged response but not in the PERMANENTFLAGS list can not be set permanently. If the client attempts to STORE a flag that isn't in the PERMANENTFLAGS list, the server will either ignore the change or store the state change for the remainder of the current session only. The PERMANENTFLAGS list can also include the special flag
\*, which indicates that it's possible to create new keywords by attempting to store those flags in the mailbox ๐ณ๏ธโ๐
- Followed by a parenthesized list of flags. It indicates which of the known flags the client can change permanently. Any flags in the FLAGS untagged response but not in the PERMANENTFLAGS list can not be set permanently. If the client attempts to STORE a flag that isn't in the PERMANENTFLAGS list, the server will either ignore the change or store the state change for the remainder of the current session only. The PERMANENTFLAGS list can also include the special flag
READ-ONLY- The mailbox is selected read-only, or its access while selected has changed from read-write to read-only ๐
READ-WRITE- The mailbox is selected read-write, or its access while selected has changed from read-only to read-write โ๏ธ
TRYCREATE- An APPEND or COPY attempt is failing because the target mailbox does not exist (as opposed to some other reason). This is a hint that the operation can succeed if the mailbox is first created by the CREATE command ๐ ๏ธ
UIDNEXT- Followed by a decimal number. It indicates the next unique identifier value. Refer to section 2.3.1.1 for more information ๐ข
UIDVALIDITY- Followed by a decimal number. It indicates the unique identifier validity value. Refer to section 2.3.1.1 for more information ๐๏ธ
UNSEEN- Followed by a decimal number. It indicates the number of the first message without the
\Seenflag set ๐๏ธ
- Followed by a decimal number. It indicates the number of the first message without the
Additional response codes defined by particular client or server implementations SHOULD be prefixed with an "X" until they're added to a revision of this protocol ๐ท Client implementations SHOULD ignore response codes they don't recognize, so no drama ๐ซ
7.1.1. OK Response โ
- Contents: OPTIONAL response code, human-readable text
The OK response is an information message from the server ๐โโ๏ธ When tagged, it means the associated command finished successfully ๐ฅณ The human-readable text MAY be presented to the user as an information message. The untagged form is info-only, and the nature of that info MAY be indicated by a response code ๐
The untagged form also shows up as one of three possible greetings at connection startup. It tells you the connection isn't authenticated yet and a LOGIN command is needed ๐
Example:
S: * OK IMAP4rev1 server ready
C: A001 LOGIN fred blurdybloop
S: * OK [ALERT] System shutdown in 10 minutes
S: A001 OK LOGIN Completed
7.1.2. NO Response ๐
Contents:
- OPTIONAL response code
- human-readable text
okay so the NO response is the server's way of saying "hmm, that didn't go well" ๐ฌ It's an operational error message. When it's tagged, it means your command didn't complete successfully ๐ When it's untagged, it's more of a heads-up or a warning ๐จ The command can still finish fine, so don't panic yet. The human-readable text tells you what's going on โจ
Example:
C: A222 COPY 1:2 owatagusiam
S: * NO Disk is 98% full, please delete unnecessary data
S: A222 OK COPY completed
C: A223 COPY 3:200 blurdybloop
S: * NO Disk is 98% full, please delete unnecessary data
S: * NO Disk is 99% full, please delete unnecessary data
S: A223 NO COPY failed: disk is full
7.1.3. BAD Response ๐
Contents:
- OPTIONAL response code
- human-readable text
the BAD response is the server going "ummm, that's not valid, bestie" ๐ It's an error message. When it's tagged, it means your command had a protocol-level error, and the tag tells you exactly which command caused it ๐ฏ When it's untagged, the server can't figure out which command caused the problem, or something internal went wrong on its end ๐ง Either way, the human-readable text explains it โจ
Example:
C: ...very long command line...
S: * BAD Command line too long
C: ...empty line...
S: * BAD Empty command line
C: A443 EXPUNGE
S: * BAD Disk crash, attempting salvage to a new disk!
S: * OK Salvage successful, no data lost
S: A443 OK Expunge completed
7.1.4. PREAUTH Response ๐
Contents:
- OPTIONAL response code
- human-readable text
the PREAUTH response is ALWAYS untagged and is one of three possible greetings when you first connect ๐ธ It's giving "you're already in, no login needed" ๐ It means the connection was already authenticated by some external method, so you don't have to send a LOGIN command. Main character energy, no password required ๐ฆ
Example:
S: * PREAUTH IMAP4rev1 server logged in as Smith
7.1.5. BYE Response ๐
Contents:
- OPTIONAL response code
- human-readable text
the BYE response is always untagged, and it means the server is about to close the connection ๐ญ The human-readable text MAY be displayed to the user in a status report by the client, so your app can show it to people ๐ซถ
The BYE response gets sent under one of four conditions:
- as part of a normal logout sequence. The server will close the connection after sending the tagged OK response to the LOGOUT command.
- as a panic shutdown announcement. The server closes the connection immediately.
- as an announcement of an inactivity autologout. The server closes the connection immediately.
- as one of three possible greetings at connection startup, indicating that the server is not willing to accept a connection from this client. The server closes the connection immediately.
the big difference is that a BYE from a normal LOGOUT (case 1) is just a graceful goodbye ๐ฅฐ A BYE because something went wrong (cases 2, 3, and 4) means the connection drops immediately, no warning, no nothing ๐ In every single case, the client SHOULD keep reading response data from the server until the connection is closed. That way any pending untagged or completion responses still get read and processed. Don't be the person who hangs up mid-sentence ๐
Example:
S: * BYE Autologout; idle for too long
7.2. Server Responses - Server and Mailbox Status ๐
these responses are ALWAYS untagged ๐ This is how the server and mailbox status data gets sent over to the client. A lot of these usually come back as a result of a command with the same name ๐
7.2.1. CAPABILITY Response โจ
Contents:
- capability listing
the CAPABILITY response shows up after you send a CAPABILITY command ๐ง The listing is a space-separated list of the capability names the server supports. The listing MUST include the atom "IMAP4rev1" ๐
Also, client and server implementations MUST implement the STARTTLS, LOGINDISABLED, and AUTH=PLAIN capabilities (the last one is described in [IMAP-TLS]) ๐ Check the Security Considerations section for the important stuff ๐
a capability name that starts with "AUTH=" tells you the server supports that specific authentication mechanism ๐
the LOGINDISABLED capability means LOGIN is switched off ๐ซ The server will reply with a tagged NO to any LOGIN attempt, even if the username and password are totally valid. An IMAP client MUST NOT issue the LOGIN command if the server advertises the LOGINDISABLED capability. Don't even try, bestie ๐ โโ๏ธ
other capability names mean the server supports some extension, revision, or amendment to the IMAP4rev1 protocol ๐ฆ Server responses MUST conform to this document until the client issues a command that uses the associated capability.
capability names MUST either begin with "X" or be standard or standards-track IMAP4rev1 extensions, revisions, or amendments registered with IANA ๐ A server MUST NOT offer unregistered or non-standard capability names, unless those names are prefixed with an "X". No sneaky names allowed ๐ต๏ธโโ๏ธ
client implementations SHOULD NOT require any capability name other than "IMAP4rev1", and MUST ignore any unknown capability names ๐ซถ Be chill about it.
a server MAY send capabilities automatically. It can use the CAPABILITY response code in the initial PREAUTH or OK responses, and also send an updated CAPABILITY response code in the tagged OK response after a successful authentication. If your client already recognizes these automatic capabilities, you don't need to send a separate CAPABILITY command. Big time-saver ๐คฉ
Example:
S: * CAPABILITY IMAP4rev1 STARTTLS AUTH=GSSAPI XPIG-LATIN
7.2.2. LIST Response ๐
Contents:
- name attributes
- hierarchy delimiter
- name
the LIST response comes back as a result of a LIST command ๐๏ธ It returns a single name that matches the LIST specification, and there can be multiple LIST responses for one LIST command ๐
Four name attributes are defined:
\Noinferiors: it's not possible for any child levels of hierarchy to exist under this name. No child levels exist now, and none can be created in the future ๐ซ\Noselect: it's not possible to use this name as a selectable mailbox ๐ โโ๏ธ\Marked: the server has marked the mailbox as "interesting". It probably has messages added since the last time it was selected ๐ฌ\Unmarked: the mailbox doesn't have any additional messages since the last time it was selected ๐
if it isn't feasible for the server to figure out whether a mailbox is "interesting", or if the name is a \Noselect name, the server SHOULD NOT send either \Marked or \Unmarked ๐คทโโ๏ธ
the hierarchy delimiter is the character used to separate levels of hierarchy in a mailbox name ๐ณ Clients use it to make child mailboxes and to search higher or lower in the naming hierarchy. All children of a top-level hierarchy node MUST use the same separator character ๐งฉ A NIL hierarchy delimiter means there's no hierarchy at all, and the name is a "flat" name ๐ฅ
the name represents an unambiguous left-to-right hierarchy, and it MUST be valid for use as a reference in LIST and LSUB commands ๐ Unless \Noselect is indicated, the name MUST also be valid as an argument for commands, such as SELECT, that accept mailbox names โจ
Example:
S: * LIST (\Noselect) "/" ~/Mail/foo
7.2.3. LSUB Response ๐ท
Contents:
- name attributes
- hierarchy delimiter
- name
the LSUB response shows up as a result of an LSUB command ๐ซ It returns a single name that matches the LSUB specification, and you can get multiple LSUB responses for one LSUB command ๐ The data is identical in format to the LIST response, so you already know how to read it ๐ง
Example:
S: * LSUB () "." #news.comp.mail.misc
7.2.4 STATUS Response ๐
Contents:
- name
- status parenthesized list
the STATUS response comes back as a result of a STATUS command ๐ It returns the mailbox name that matches the STATUS specification, along with the mailbox status info you asked for ๐
Example:
S: * STATUS blurdybloop (MESSAGES 231 UIDNEXT 44292)
7.2.5. SEARCH Response ๐
Contents:
- zero or more numbers
the SEARCH response shows up after a SEARCH or UID SEARCH command ๐ฏ The numbers are the messages that match your search criteria. For SEARCH, they're message sequence numbers. For UID SEARCH, they're unique identifiers. Each number is separated by a space ๐ซง
Example:
S: * SEARCH 2 3 6
7.2.6. FLAGS Response ๐ฉ
Contents:
- flag parenthesized list
the FLAGS response happens as a result of a SELECT or EXAMINE command ๐ The flag parenthesized list tells you which flags apply to this mailbox. At minimum you get the system-defined flags, and depending on the server, there can be other flags too ๐
The update from the FLAGS response MUST be recorded by the client. No skipping this one, bestie ๐
Example:
S: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
7.3. Server Responses - Mailbox Size ๐
these responses are ALWAYS untagged ๐ This is how changes in the size of the mailbox get sent from the server to the client. Right after the "*" token, you'll see a number that represents a message count ๐ข
7.3.1. EXISTS Response ๐ธ
Contents:
- none
the EXISTS response reports how many messages are in the mailbox โจ It comes back as a result of a SELECT or EXAMINE command, and also whenever the size of the mailbox changes (like when new messages arrive) ๐ฌ
The update from the EXISTS response MUST be recorded by the client ๐
Example:
S: * 23 EXISTS
7.3.2. RECENT Response ๐
Contents:
- none
the RECENT response reports how many messages have the \Recent flag set ๐ท๏ธ It comes back as a result of a SELECT or EXAMINE command, and also whenever the size of the mailbox changes (like new messages showing up) ๐ซ
Note: It is not guaranteed that the message sequence numbers of recent messages will be a contiguous range of the highest n messages in the mailbox (where n is the value reported by the RECENT response). Examples of situations in which this is not the case are: multiple clients having the same mailbox open (the first session to be notified will see it as recent, others will probably see it as non-recent), and when the mailbox is re-ordered by a non-IMAP agent. The only reliable way to identify recent messages is to look at message flags to see which have the \Recent flag set, or to do a SEARCH RECENT.
the update from the RECENT response MUST be recorded by the client ๐ซถ
Example:
S: * 5 RECENT
7.4. Server Responses - Message Status ๐ง
these responses are ALWAYS untagged ๐ This is how message data gets sent from the server to the client, often as a result of a command with the same name. Right after the "*" token, you'll see a number that represents a message sequence number ๐
7.4.1. EXPUNGE Response โจ
Contents: none ๐ซถ
okay bestie, the EXPUNGE response is literally the server going "bye, message 44, you're gone" ๐ฆ It tells you that the specified message sequence number has been permanently removed from the mailbox. Every message after it gets its sequence number knocked down by 1 right away, and that shift shows up in every sequence number in later responses too (including other untagged EXPUNGE responses). no cap, the math is instant ๐
The EXPUNGE response also lowers the message count in the mailbox, so you don't need to send an EXISTS response with the new number ๐ธ
Okay, this part is so iconic it's giving math class ๐ง Because of that instant decrement, the sequence numbers you see in a bunch of EXPUNGE responses depend on the order the messages get removed. Say the last 5 messages in a 9-message mailbox get expunged. A "lower to higher" server sends five untagged EXPUNGE responses, all for sequence number 5. A "higher to lower server" sends them for 9, 8, 7, 6, and 5, in that order. ๐ญ
An EXPUNGE response MUST NOT be sent when no command is in progress, nor while responding to a FETCH, STORE, or SEARCH command. This rule is super necessary to stop the client and server from losing track of sequence numbers ๐ A command doesn't count as "in progress" until the whole command has been received. Specifically, it isn't "in progress" during the negotiation of command continuation.
Note: UID FETCH, UID STORE, and UID SEARCH are different commands from FETCH, STORE, and SEARCH. An EXPUNGE response MAY be sent during a UID command.
The update from the EXPUNGE response MUST be recorded by the client. Non-negotiable, periodt ๐
Example:
S: * 44 EXPUNGE
7.4.2. FETCH Response ๐
Contents: message data
The FETCH response sends data about a message back to the client ๐ง The data comes as pairs of data item names and their values, wrapped in parentheses. This response shows up because of a FETCH or STORE command, and also when the server decides on its own to send it (for example, flag updates).
The current data items are:
BODY- A form of BODYSTRUCTURE without extension data.
BODY[<section>]<<origin octet>>- A string with the body contents of the specified section. The client SHOULD interpret this string according to the content transfer encoding, body type, and subtype.
- If the origin octet is specified, this string is a substring of the entire body contents, starting at that origin octet. This means that
BODY[]<0>MAY be truncated, butBODY[]is NEVER truncated. ๐ - > Note: The origin octet facility MUST NOT be used by a server in a FETCH response unless the client specifically requested it by means of a FETCH of a
BODY[<section>]<<partial>>data item. - 8-bit textual data is permitted if a [CHARSET] identifier is part of the body parameter parenthesized list for this section. Heads up though: headers (part specifiers HEADER or MIME, or the header portion of a MESSAGE/RFC822 part) MUST be 7-bit, so 8-bit characters are not allowed in headers ๐ โโ๏ธ Also, the [RFC-2822] delimiting blank line between the header and the body isn't affected by header line subsetting. The blank line is always part of the header data, except when a message has no body and no blank line.
- Non-textual data, like binary data, MUST be transfer encoded into a textual form, such as BASE64, before it gets sent to the client. To get the original binary data back, the client MUST decode the transfer encoded string ๐ฅ
BODYSTRUCTURE- A parenthesized list that describes the [MIME-IMB] body structure of a message. The server works this out by parsing the [MIME-IMB] header fields and filling in defaults for various fields as needed.
- For example, a simple text message of 48 lines and 2279 octets can have a body structure of:
("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 2279 48)
- Multiple parts are shown with parenthesis nesting. Instead of a body type as the first element of the parenthesized list, there's a sequence of one or more nested body structures. The second element of the parenthesized list is the multipart subtype (mixed, digest, parallel, alternative, etc.) โจ
- For example, a two part message made of a text part and a BASE64-encoded text attachment can have a body structure of:
(("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152
23)("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff")
"<960723163407.20117h@cac.washington.edu>" "Compiler diff"
"BASE64" 4554 73) "MIXED")
- Extension data follows the multipart subtype. Extension data is never returned with the BODY fetch, but it can come back with a BODYSTRUCTURE fetch. Extension data, if present, MUST be in the defined order. For a multipart body part, the extension data goes in this order:
- body parameter parenthesized list: a parenthesized list of attribute/value pairs [e.g., ("foo" "bar" "baz" "rag") where "bar" is the value of "foo", and "rag" is the value of "baz"] as defined in [MIME-IMB].
- body disposition: a parenthesized list, made of a disposition type string followed by a parenthesized list of disposition attribute/value pairs as defined in [DISPOSITION].
- body language: a string or parenthesized list giving the body language value as defined in [LANGUAGE-TAGS].
- body location: a string list giving the body content URI as defined in [LOCATION].
- Any extension data after that isn't defined yet in this version of the protocol. It can be made of zero or more NILs, strings, numbers, or possibly nested parenthesized lists of that stuff. Client implementations that do a BODYSTRUCTURE fetch MUST be prepared to accept that extension data. Server implementations MUST NOT send that extension data until a revision of this protocol has defined it ๐ซถ
- The basic fields of a non-multipart body part go in this order:
- body type: a string giving the content media type name as defined in [MIME-IMB].
- body subtype: a string giving the content subtype name as defined in [MIME-IMB].
- body parameter parenthesized list: a parenthesized list of attribute/value pairs [e.g., ("foo" "bar" "baz" "rag") where "bar" is the value of "foo" and "rag" is the value of "baz"] as defined in [MIME-IMB].
- body id: a string giving the content id as defined in [MIME-IMB].
- body description: a string giving the content description as defined in [MIME-IMB].
- body encoding: a string giving the content transfer encoding as defined in [MIME-IMB].
- body size: a number giving the size of the body in octets. Note that this size is the size in its transfer encoding, not the size after any decoding.
- A body type of MESSAGE and subtype RFC822 contains, right after the basic fields, the envelope structure, body structure, and size in text lines of the encapsulated message.
- A body type of TEXT contains, right after the basic fields, the size of the body in text lines. Note that this size is the size in its content transfer encoding, not the size after any decoding.
- Extension data follows the basic fields and the type-specific fields listed above. Extension data is never returned with the BODY fetch, but it can be returned with a BODYSTRUCTURE fetch. Extension data, if present, MUST be in the defined order.
- The extension data of a non-multipart body part goes in this order:
- body MD5: a string giving the body MD5 value as defined in [MD5].
- body disposition: a parenthesized list with the same content and function as the body disposition for a multipart body part.
- body language: a string or parenthesized list giving the body language value as defined in [LANGUAGE-TAGS].
- body location: a string list giving the body content URI as defined in [LOCATION].
- Any extension data after that isn't defined yet in this version of the protocol, and it works the same way as the multipart extension data described above ๐
ENVELOPE- A parenthesized list that describes the envelope structure of a message. The server makes this by parsing the [RFC-2822] header into its component parts and filling in defaults for various fields as needed ๐ฌ
- The fields of the envelope structure go in this order: date, subject, from, sender, reply-to, to, cc, bcc, in-reply-to, and message-id. The date, subject, in-reply-to, and message-id fields are strings. The from, sender, reply-to, to, cc, and bcc fields are parenthesized lists of address structures.
- An address structure is a parenthesized list that describes an electronic mail address. Its fields go in this order: personal name, [SMTP] at-domain-list (source route), mailbox name, and host name.
- [RFC-2822] group syntax is shown with a special form of address structure where the host name field is NIL. If the mailbox name field is also NIL, it's an end of group marker (semi-colon in RFC 822 syntax). If the mailbox name field isn't NIL, it's a start of group marker, and the mailbox name field holds the group name phrase ๐
- If the Date, Subject, In-Reply-To, and Message-ID header lines are missing from the [RFC-2822] header, the matching member of the envelope is NIL. If those header lines are there but empty, the matching member of the envelope is the empty string.
- > Note: some servers may return a NIL envelope member in the "present but empty" case. Clients SHOULD treat NIL and empty string as identical.
- > Note: [RFC-2822] requires that all messages have a valid Date header. So the date member in the envelope can't be NIL or the empty string.
- > Note: [RFC-2822] requires that the In-Reply-To and Message-ID headers, if present, have non-empty content. So the in-reply-to and message-id members in the envelope can't be the empty string.
- If the From, To, cc, and bcc header lines are missing from the [RFC-2822] header, or are there but empty, the matching member of the envelope is NIL.
Okay bestie, the FETCH stuff is done, so let's keep going ๐ โจ
If the Sender or Reply-To lines are absent in the [RFC-2822] header, or are present but empty, the server sets the corresponding member of the envelope to be the same value as the from member (the client is not expected to know to do this). The server handles that fallback so the client doesn't have to ๐ซถ
Note: [RFC-2822] requires that all messages have a valid From header. Therefore, the from, sender, and reply-to members in the envelope can not be NIL. ๐
FLAGS: a parenthesized list of flags that are set for this message ๐INTERNALDATE: a string representing the internal date of the message ๐ธRFC822: equivalent toBODY[]๐ฆRFC822.HEADER: equivalent toBODY[HEADER]. Plot twist: this did not result in\Seenbeing set, becauseRFC822.HEADERresponse data shows up as a result of a FETCH ofRFC822.HEADER.BODY[HEADER]response data shows up from a FETCH ofBODY[HEADER](which sets\Seen) orBODY.PEEK[HEADER](which does not set\Seen) ๐๐RFC822.SIZE: a number expressing the [RFC-2822] size of the message ๐RFC822.TEXT: equivalent toBODY[TEXT]๐งUID: a number expressing the unique identifier of the message ๐ฅ
Example:
S: * 23 FETCH (FLAGS (\Seen) RFC822.SIZE 44827)
7.5. Server Responses - Command Continuation Request โจ
The command continuation request response is indicated by a "+" token instead of a tag. This form of response means the server is ready to accept the continuation of a command from the client. The rest of this response is a line of text ๐
This response is used in the AUTHENTICATE command to transmit server data to the client, and to request additional client data. It also shows up if an argument to any command is a literal ๐
The client is not permitted to send the octets of the literal unless the server indicates that it is expected. This lets the server process commands and reject errors on a line-by-line basis ๐ง The rest of the command, including the CRLF that terminates a command, follows the octets of the literal. If there are any additional command arguments, the literal octets are followed by a space and those arguments ๐ซถ
Example:
C: A001 LOGIN {11}
S: + Ready for additional command text
C: FRED FOOBAR {7}
S: + Ready for additional command text
C: fat man
S: A001 OK LOGIN completed
C: A044 BLURDYBLOOP {102856}
S: A044 BAD No such command as "BLURDYBLOOP"
8. Sample IMAP4rev1 connection ๐
The following is a transcript of an IMAP4rev1 connection. A long line in this sample is broken for editorial clarity ๐ฆ
S: * OK IMAP4rev1 Service Ready
C: a001 login mrc secret
S: a001 OK LOGIN completed
C: a002 select inbox
S: * 18 EXISTS
S: * FLAGS (\Answered \Flagged \Deleted \Seen \Draft)
S: * 2 RECENT
S: * OK [UNSEEN 17] Message 17 is the first unseen message
S: * OK [UIDVALIDITY 3857529045] UIDs valid
S: a002 OK [READ-WRITE] SELECT completed
C: a003 fetch 12 full
S: * 12 FETCH (FLAGS (\Seen) INTERNALDATE "17-Jul-1996 02:44:25 -0700"
RFC822.SIZE 4286 ENVELOPE ("Wed, 17 Jul 1996 02:23:25 -0700 (PDT)"
"IMAP4rev1 WG mtg summary and minutes"
(("Terry Gray" NIL "gray" "cac.washington.edu"))
(("Terry Gray" NIL "gray" "cac.washington.edu"))
(("Terry Gray" NIL "gray" "cac.washington.edu"))
((NIL NIL "imap" "cac.washington.edu"))
((NIL NIL "minutes" "CNRI.Reston.VA.US")
("John Klensin" NIL "KLENSIN" "MIT.EDU")) NIL NIL
"<B27397-0100000@cac.washington.edu>")
BODY ("TEXT" "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 3028
92))
S: a003 OK FETCH completed
C: a004 fetch 12 body[header]
S: * 12 FETCH (BODY[HEADER] {342}
S: Date: Wed, 17 Jul 1996 02:23:25 -0700 (PDT)
S: From: Terry Gray <gray@cac.washington.edu>
S: Subject: IMAP4rev1 WG mtg summary and minutes
S: To: imap@cac.washington.edu
S: cc: minutes@CNRI.Reston.VA.US, John Klensin <KLENSIN@MIT.EDU>
S: Message-Id: <B27397-0100000@cac.washington.edu>
S: MIME-Version: 1.0
S: Content-Type: TEXT/PLAIN; CHARSET=US-ASCII
S:
S: )
S: a004 OK FETCH completed
C: a005 store 12 +flags \deleted
S: * 12 FETCH (FLAGS (\Seen \Deleted))
S: a005 OK +FLAGS completed
C: a006 logout
S: * BYE IMAP4rev1 server terminating connection
S: a006 OK LOGOUT completed
9. Formal Syntax ๐
The following syntax specification uses the Augmented Backus-Naur Form (ABNF) notation as specified in [ABNF]. Time to get technical, bestie ๐ค
In the case of alternative or optional rules in which a later rule overlaps an earlier rule, the rule which is listed earlier MUST take priority. For example, "\Seen" when parsed as a flag is the \Seen flag name and not a flag-extension, even though "\Seen" can be parsed as a flag-extension. Some, but not all, instances of this rule are noted below ๐ฅ
Note: [ABNF] rules MUST be followed strictly; in particular:
- Except as noted otherwise, all alphabetic characters are case-insensitive. The use of upper or lower case characters to define token strings is for editorial clarity only. Implementations MUST accept these strings in a case-insensitive fashion. ๐
- In all cases, SP refers to exactly one space. It is absolutely not permitted to substitute TAB, insert additional spaces, or otherwise treat SP as being equivalent to LWSP. ๐
- The ASCII NUL character,
%x00, MUST NOT be used at any time. ๐
address = "(" addr-name SP addr-adl SP addr-mailbox SP
addr-host ")"
addr-adl = nstring
; Holds route from [RFC-2822] route-addr if
; non-NIL
addr-host = nstring
; NIL indicates [RFC-2822] group syntax.
; Otherwise, holds [RFC-2822] domain name
addr-mailbox = nstring
; NIL indicates end of [RFC-2822] group; if
; non-NIL and addr-host is NIL, holds
; [RFC-2822] group name.
; Otherwise, holds [RFC-2822] local-part
; after removing [RFC-2822] quoting
addr-name = nstring
; If non-NIL, holds phrase from [RFC-2822]
; mailbox after removing [RFC-2822] quoting
append = "APPEND" SP mailbox [SP flag-list] [SP date-time] SP
literal
astring = 1*ASTRING-CHAR / string
ASTRING-CHAR = ATOM-CHAR / resp-specials
atom = 1*ATOM-CHAR
ATOM-CHAR = <any CHAR except atom-specials>
atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
quoted-specials / resp-specials
authenticate = "AUTHENTICATE" SP auth-type *(CRLF base64)
auth-type = atom
; Defined by [SASL]
base64 = *(4base64-char) [base64-terminal]
base64-char = ALPHA / DIGIT / "+" / "/"
; Case-sensitive
base64-terminal = (2base64-char "==") / (3base64-char "=")
body = "(" (body-type-1part / body-type-mpart) ")"
body-extension = nstring / number /
"(" body-extension *(SP body-extension) ")"
; Future expansion. Client implementations
; MUST accept body-extension fields. Server
; implementations MUST NOT generate
; body-extension fields except as defined by
; future standard or standards-track
; revisions of this specification.
body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
[SP body-fld-loc *(SP body-extension)]]]
; MUST NOT be returned on non-extensible
; "BODY" fetch
body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
[SP body-fld-loc *(SP body-extension)]]]
; MUST NOT be returned on non-extensible
; "BODY" fetch
body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
body-fld-enc SP body-fld-octets
body-fld-desc = nstring
body-fld-dsp = "(" string SP body-fld-param ")" / nil
body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
"QUOTED-PRINTABLE") DQUOTE) / string
body-fld-id = nstring
body-fld-lang = nstring / "(" string *(SP string) ")"
body-fld-loc = nstring
body-fld-lines = number
body-fld-md5 = nstring
body-fld-octets = number
body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
body-type-1part = (body-type-basic / body-type-msg / body-type-text)
[SP body-ext-1part]
body-type-basic = media-basic SP body-fields
; MESSAGE subtype MUST NOT be "RFC822"
body-type-mpart = 1*body SP media-subtype
[SP body-ext-mpart]
body-type-msg = media-message SP body-fields SP envelope
SP body SP body-fld-lines
body-type-text = media-text SP body-fields SP body-fld-lines
capability = ("AUTH=" auth-type) / atom
; New capabilities MUST begin with "X" or be
; registered with IANA as standard or
; standards-track
capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
*(SP capability)
; Servers MUST implement the STARTTLS, AUTH=PLAIN,
; and LOGINDISABLED capabilities
; Servers which offer RFC 1730 compatibility MUST
; list "IMAP4" as the first capability.
CHAR8 = %x01-ff
; any OCTET except NUL, %x00
command = tag SP (command-any / command-auth / command-nonauth /
command-select) CRLF
; Modal based on state
command-any = "CAPABILITY" / "LOGOUT" / "NOOP" / x-command
; Valid in all states
command-auth = append / create / delete / examine / list / lsub /
rename / select / status / subscribe / unsubscribe
; Valid only in Authenticated or Selected state
command-nonauth = login / authenticate / "STARTTLS"
; Valid only when in Not Authenticated state
command-select = "CHECK" / "CLOSE" / "EXPUNGE" / copy / fetch / store /
uid / search
; Valid only when in Selected state
continue-req = "+" SP (resp-text / base64) CRLF
copy = "COPY" SP sequence-set SP mailbox
create = "CREATE" SP mailbox
; Use of INBOX gives a NO error
date = date-text / DQUOTE date-text DQUOTE
date-day = 1*2DIGIT
; Day of month
date-day-fixed = (SP DIGIT) / 2DIGIT
; Fixed-format version of date-day
date-month = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" /
"Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec"
date-text = date-day "-" date-month "-" date-year
date-year = 4DIGIT
date-time = DQUOTE date-day-fixed "-" date-month "-" date-year
SP time SP zone DQUOTE
delete = "DELETE" SP mailbox
; Use of INBOX gives a NO error
digit-nz = %x31-39
; 1-9
envelope = "(" env-date SP env-subject SP env-from SP
env-sender SP env-reply-to SP env-to SP env-cc SP
env-bcc SP env-in-reply-to SP env-message-id ")"
env-bcc = "(" 1*address ")" / nil
env-cc = "(" 1*address ")" / nil
env-date = nstring
env-from = "(" 1*address ")" / nil
env-in-reply-to = nstring
Okay bestie, the grammar is back and it's giving organised chaos ๐ Every rule stays exactly as written, so grab a ๐ and let's go.
env-message-id, env-reply-to, env-sender, env-subject and env-to are all the little envelope pieces, and each address list is wrapped in brackets or it's just NIL ๐
env-message-id = nstring
env-reply-to = "(" 1*address ")" / nil
env-sender = "(" 1*address ")" / nil
env-subject = nstring
env-to = "(" 1*address ")" / nil
examine = "EXAMINE" SP mailbox
fetch = "FETCH" SP sequence-set SP ("ALL" / "FULL" / "FAST" /
fetch-att / "(" fetch-att *(SP fetch-att) ")")
fetch-att = "ENVELOPE" / "FLAGS" / "INTERNALDATE" /
"RFC822" [".HEADER" / ".SIZE" / ".TEXT"] /
"BODY" ["STRUCTURE"] / "UID" /
"BODY" section ["<" number "." nz-number ">"] /
"BODY.PEEK" section ["<" number "." nz-number ">"]
flag = "\Answered" / "\Flagged" / "\Deleted" /
"\Seen" / "\Draft" / flag-keyword / flag-extension
; Does not include "\Recent"
flag-extension = "\" atom
; Future expansion. Client implementations
; MUST accept flag-extension flags. Server
; implementations MUST NOT generate
; flag-extension flags except as defined by
; future standard or standards-track
; revisions of this specification.
flag-fetch = flag / "\Recent"
flag-keyword = atom
flag-list = "(" [flag *(SP flag)] ")"
flag-perm = flag / "\*"
greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
header-fld-name = astring
header-list = "(" header-fld-name *(SP header-fld-name) ")"
list = "LIST" SP mailbox SP list-mailbox
list-mailbox = 1*list-char / string
list-char = ATOM-CHAR / list-wildcards / resp-specials
list-wildcards = "%" / "*"
literal = "{" number "}" CRLF *CHAR8
; Number represents the number of CHAR8s
login = "LOGIN" SP userid SP password
lsub = "LSUB" SP mailbox SP list-mailbox
Now the flag stuff, which is a whole vibe ๐ฆ Clients accept flag-extension flags, but servers only make the ones a standard defines, and "\Recent" is NOT part of flag, it's only in flag-fetch ๐
And mailbox! INBOX is case-insensitive, so every "iNbOx" style spelling counts as INBOX and never as a plain astring. Section 5.1 has the extra mailbox-name details ๐ง
mailbox = "INBOX" / astring
; INBOX is case-insensitive. All case variants of
; INBOX (e.g., "iNbOx") MUST be interpreted as INBOX
; not as an astring. An astring which consists of
; the case-insensitive sequence "I" "N" "B" "O" "X"
; is considered to be INBOX and not an astring.
; Refer to section 5.1 for further
; semantic details of mailbox names.
mailbox-data = "FLAGS" SP flag-list / "LIST" SP mailbox-list /
"LSUB" SP mailbox-list / "SEARCH" *(SP nz-number) /
"STATUS" SP mailbox SP "(" [status-att-list] ")" /
number SP "EXISTS" / number SP "RECENT"
mailbox-list = "(" [mbx-list-flags] ")" SP
(DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
*(SP mbx-list-oflag) /
mbx-list-oflag *(SP mbx-list-oflag)
mbx-list-oflag = "\Noinferiors" / flag-extension
; Other flags; multiple possible per LIST response
mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
; Selectability flags; only one per LIST response
media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
"MESSAGE" / "VIDEO") DQUOTE) / string) SP
media-subtype
; Defined in [MIME-IMT]
media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
; Defined in [MIME-IMT]
media-subtype = string
; Defined in [MIME-IMT]
media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
; Defined in [MIME-IMT]
message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
msg-att = "(" (msg-att-dynamic / msg-att-static)
*(SP (msg-att-dynamic / msg-att-static)) ")"
msg-att-dynamic = "FLAGS" SP "(" [flag-fetch *(SP flag-fetch)] ")"
; MAY change for a message
msg-att-static = "ENVELOPE" SP envelope / "INTERNALDATE" SP date-time /
"RFC822" [".HEADER" / ".TEXT"] SP nstring /
"RFC822.SIZE" SP number /
"BODY" ["STRUCTURE"] SP body /
"BODY" section ["<" number ">"] SP nstring /
"UID" SP uniqueid
; MUST NOT change for a message
nil = "NIL"
nstring = string / nil
number = 1*DIGIT
; Unsigned 32-bit integer
; (0 <= n < 4,294,967,296)
nz-number = digit-nz *DIGIT
; Non-zero unsigned 32-bit integer
; (0 < n < 4,294,967,296)
password = astring
quoted = DQUOTE *QUOTED-CHAR DQUOTE
QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
"\" quoted-specials
quoted-specials = DQUOTE / "\"
rename = "RENAME" SP mailbox SP mailbox
; Use of INBOX as a destination gives a NO error
response = *(continue-req / response-data) response-done
response-data = "*" SP (resp-cond-state / resp-cond-bye /
mailbox-data / message-data / capability-data) CRLF
response-done = response-tagged / response-fatal
response-fatal = "*" SP resp-cond-bye CRLF
; Server closes connection immediately
response-tagged = tag SP resp-cond-state CRLF
resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
; Authentication condition
resp-cond-bye = "BYE" SP resp-text
resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
; Status condition
resp-specials = "]"
resp-text = ["[" resp-text-code "]" SP] text
resp-text-code = "ALERT" /
"BADCHARSET" [SP "(" astring *(SP astring) ")" ] /
capability-data / "PARSE" /
"PERMANENTFLAGS" SP "("
[flag-perm *(SP flag-perm)] ")" /
"READ-ONLY" / "READ-WRITE" / "TRYCREATE" /
"UIDNEXT" SP nz-number / "UIDVALIDITY" SP nz-number /
"UNSEEN" SP nz-number /
atom [SP 1*<any TEXT-CHAR except "]">]
Search time! โจ The CHARSET argument to SEARCH MUST be registered with IANA, and the search-key list is HUGE, with the old IMAP2 keys sitting right above a little comment line ๐
search = "SEARCH" [SP "CHARSET" SP astring] 1*(SP search-key)
; CHARSET argument to MUST be registered with IANA
search-key = "ALL" / "ANSWERED" / "BCC" SP astring /
"BEFORE" SP date / "BODY" SP astring /
"CC" SP astring / "DELETED" / "FLAGGED" /
"FROM" SP astring / "KEYWORD" SP flag-keyword /
"NEW" / "OLD" / "ON" SP date / "RECENT" / "SEEN" /
"SINCE" SP date / "SUBJECT" SP astring /
"TEXT" SP astring / "TO" SP astring /
"UNANSWERED" / "UNDELETED" / "UNFLAGGED" /
"UNKEYWORD" SP flag-keyword / "UNSEEN" /
; Above this line were in [IMAP2]
"DRAFT" / "HEADER" SP header-fld-name SP astring /
"LARGER" SP number / "NOT" SP search-key /
"OR" SP search-key SP search-key /
"SENTBEFORE" SP date / "SENTON" SP date /
"SENTSINCE" SP date / "SMALLER" SP number /
"UID" SP sequence-set / "UNDRAFT" / sequence-set /
"(" search-key *(SP search-key) ")"
section = "[" [section-spec] "]"
section-msgtext = "HEADER" / "HEADER.FIELDS" [".NOT"] SP header-list /
"TEXT"
; top-level or MESSAGE/RFC822 part
section-part = nz-number *("." nz-number)
; body part nesting
section-spec = section-msgtext / (section-part ["." section-text])
section-text = section-msgtext / "MIME"
; text other than actual body part (headers, etc.)
select = "SELECT" SP mailbox
Sequence numbers are where things get spicy ๐ The "" means the biggest number in use, and a tagged BAD is the server's reply if you point past the end. Servers MAY coalesce overlaps or run the sequence in any order, so 2,4:7,9,12: and friends are all fair game ๐
seq-number = nz-number / "*"
; message sequence number (COPY, FETCH, STORE
; commands) or unique identifier (UID COPY,
; UID FETCH, UID STORE commands).
; * represents the largest number in use. In
; the case of message sequence numbers, it is
; the number of messages in a non-empty mailbox.
; In the case of unique identifiers, it is the
; unique identifier of the last message in the
; mailbox or, if the mailbox is empty, the
; mailbox's current UIDNEXT value.
; The server should respond with a tagged BAD
; response to a command that uses a message
; sequence number greater than the number of
; messages in the selected mailbox. This
; includes "*" if the selected mailbox is empty.
seq-range = seq-number ":" seq-number
; two seq-number values and all values between
; these two regardless of order.
; Example: 2:4 and 4:2 are equivalent and indicate
; values 2, 3, and 4.
; Example: a unique identifier sequence range of
; 3291:* includes the UID of the last message in
; the mailbox, even if that value is less than 3291.
sequence-set = (seq-number / seq-range) *("," sequence-set)
; set of seq-number values, regardless of order.
; Servers MAY coalesce overlaps and/or execute the
; sequence in any order.
; Example: a message sequence number set of
; 2,4:7,9,12:* for a mailbox with 15 messages is
; equivalent to 2,4,5,6,7,9,12,13,14,15
; Example: a message sequence number set of *:4,5:7
; for a mailbox with 10 messages is equivalent to
; 10,9,8,7,6,5,4,5,6,7 and MAY be reordered and
; overlap coalesced to be 4,5,6,7,8,9,10.
status = "STATUS" SP mailbox SP
"(" status-att *(SP status-att) ")"
status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
"UNSEEN"
status-att-list = status-att SP number *(SP status-att SP number)
store = "STORE" SP sequence-set SP store-att-flags
And that's the grammar for this chunk, bestie! ๐ธโจ
store-att-flags = (["+" / "-"] "FLAGS" [".SILENT"]) SP
(flag-list / (flag *(SP flag)))
string = quoted / literal
subscribe = "SUBSCRIBE" SP mailbox
tag = 1*<any ASTRING-CHAR except "+">
text = 1*TEXT-CHAR
TEXT-CHAR = <any CHAR except CR and LF>
time = 2DIGIT ":" 2DIGIT ":" 2DIGIT
; Hours minutes seconds
uid = "UID" SP (copy / fetch / search / store)
; Unique identifiers used instead of message
; sequence numbers
uniqueid = nz-number
; Strictly ascending
unsubscribe = "UNSUBSCRIBE" SP mailbox
userid = astring
x-command = "X" atom <experimental command arguments>
zone = ("+" / "-") 4DIGIT
; Signed four-digit value of hhmm representing
; hours and minutes east of Greenwich (that is,
; the amount that the given time differs from
; Universal Time). Subtracting the timezone
; from the given time will give the UT form.
; The Universal Time zone is "+0000".
10. Author's Note โจ
okay so this document is basically a glow-up of a bunch of older documents ๐ and it supersedes the protocol specs in all of these: RFC 2060, RFC 1730, the unpublished IMAP2bis.TXT document, RFC 1176, and RFC 1064. so if you're ever wondering which one is the current main character, it's this one ๐
11. Security Considerations ๐
bestie, we need to talk about this one ๐ญ IMAP4rev1 protocol transactions, including email data, are sent in the clear over the network unless protection from snooping is negotiated. you can get that protection through STARTTLS, negotiated privacy protection in the AUTHENTICATE command, or some other protection mechanism. no cap, plaintext everywhere is a whole disaster ๐
11.1. STARTTLS Security Considerations
the STARTTLS command and LOGINDISABLED capability spec in this document replaces the one in [IMAP-TLS]. [IMAP-TLS] stays normative for the PLAIN [SASL] authenticator ๐
the cipher suite rules are a whole vibe โจ
- IMAP client and server implementations MUST implement the
TLS_RSA_WITH_RC4_128_MD5[TLS] cipher suite, and SHOULD implement theTLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA[TLS] cipher suite. this is important because it makes sure any two compliant implementations can be configured to interoperate ๐ซถ - All other cipher suites are OPTIONAL.
- Note that this is a change from section 2.1 of [IMAP-TLS].
during the [TLS] negotiation, the client MUST check its understanding of the server hostname against the server's identity as presented in the server Certificate message. this is how we stop man-in-the-middle attacks, and it's literally non-negotiable ๐ โโ๏ธ if the match fails, the client SHOULD either ask for explicit user confirmation, or terminate the connection and indicate that the server's identity is suspect. matching works like this:
- The client MUST use the server hostname it used to open the connection as the value to compare against the server name as expressed in the server certificate. The client MUST NOT use any form of the server hostname derived from an insecure remote source (e.g., insecure DNS lookup). CNAME canonicalization is not done.
- If a subjectAltName extension of type dNSName is present in the certificate, it SHOULD be used as the source of the server's identity.
- Matching is case-insensitive.
- A
*wildcard character MAY be used as the left-most name component in the certificate. For example,*.example.comwould matcha.example.com,foo.example.com, etc. but would not matchexample.com. - If the certificate contains multiple names (e.g., more than one dNSName field), then a match with any one of the fields is considered acceptable.
Both the client and server MUST check the result of the STARTTLS command and subsequent [TLS] negotiation to see whether acceptable authentication or privacy was achieved. checks are the best friend you never knew you needed ๐ฆ
11.2. Other Security Considerations
okay the password stuff is SERIOUS ๐จ so buckle up
- A server error message for an AUTHENTICATE command which fails due to invalid credentials SHOULD NOT detail why the credentials are invalid. don't spill the tea to the attacker ๐ต
- Use of the LOGIN command sends passwords in the clear. this can be avoided by using the AUTHENTICATE command with a [SASL] mechanism that does not use plaintext passwords, by first negotiating encryption via STARTTLS or some other protection mechanism ๐
now the big one: a server implementation MUST implement a configuration that, at the time of authentication, requires one of the following:
- (1) The STARTTLS command has been negotiated.
- OR
- (2) Some other mechanism that protects the session from password snooping has been provided.
- OR
- (3) The following measures are in place:
- (a) The LOGINDISABLED capability is advertised, and [SASL] mechanisms (such as PLAIN) using plaintext passwords are NOT advertised in the CAPABILITY list.
- AND
- (b) The LOGIN command returns an error even if the password is correct.
- AND
- (c) The AUTHENTICATE command returns an error with all [SASL] mechanisms that use plaintext passwords, even if the password is correct.
- A server error message for a failing LOGIN command SHOULD NOT specify that the user name, as opposed to the password, is invalid. ๐
- A server SHOULD have mechanisms in place to limit or delay failed AUTHENTICATE/LOGIN attempts. brute force said "not today" ๐
Additional security considerations are discussed in the section discussing the AUTHENTICATE and LOGIN commands.
12. IANA Considerations ๐ธ
IMAP4 capabilities are registered by publishing a standards track or IESG approved experimental RFC. the registry lives at:
http://www.iana.org/assignments/imap4-capabilities
since this spec revises the STARTTLS and LOGINDISABLED extensions that were previously defined in [IMAP-TLS], the registry will be updated accordingly ๐ง
Appendices
A. Normative References
these are the docs you need to understand this one properly, so read them like it's your job ๐
- [ABNF] Crocker, D. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", RFC 2234, November 1997.
- [ANONYMOUS] Newman, C., "Anonymous SASL Mechanism", RFC 2245, November 1997.
- [CHARSET] Freed, N. and J. Postel, "IANA Character Set Registration Procedures", RFC 2978, October 2000.
- [DIGEST-MD5] Leach, P. and C. Newman, "Using Digest Authentication as a SASL Mechanism", RFC 2831, May 2000.
- [DISPOSITION] Troost, R., Dorner, S. and K. Moore, "Communicating Presentation Information in Internet Messages: The Content-Disposition Header", RFC 2183, August 1997.
- [IMAP-TLS] Newman, C., "Using TLS with IMAP, POP3 and ACAP", RFC 2595, June 1999.
- [KEYWORDS] Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, March 1997.
- [LANGUAGE-TAGS] Alvestrand, H., "Tags for the Identification of Languages", BCP 47, RFC 3066, January 2001.
- [LOCATION] Palme, J., Hopmann, A. and N. Shelness, "MIME Encapsulation of Aggregate Documents, such as HTML (MHTML)", RFC 2557, March 1999.
- [MD5] Myers, J. and M. Rose, "The Content-MD5 Header Field", RFC 1864, October 1995.
- [MIME-HDRS] Moore, K., "MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text", RFC 2047, November 1996.
- [MIME-IMB] Freed, N. and N. Borenstein, "MIME (Multipurpose Internet Mail Extensions) Part One: Format of Internet Message Bodies", RFC 2045, November 1996.
- [MIME-IMT] Freed, N. and N. Borenstein, "MIME (Multipurpose Internet Mail Extensions) Part Two: Media Types", RFC 2046, November 1996.
- [RFC-2822] Resnick, P., "Internet Message Format", RFC 2822, April 2001.
- [SASL] Myers, J., "Simple Authentication and Security Layer (SASL)", RFC 2222, October 1997.
- [TLS] Dierks, T. and C. Allen, "The TLS Protocol Version 1.0", RFC 2246, January 1999.
- [UTF-7] Goldsmith, D. and M. Davis, "UTF-7: A Mail-Safe Transformation Format of Unicode", RFC 2152, May 1997.
these ones describe quality-of-implementation issues that should be carefully considered when you're implementing this protocol ๐ง
- [IMAP-IMPLEMENTATION] Leiba, B., "IMAP Implementation Recommendations", RFC 2683, September 1999.
- [IMAP-MULTIACCESS] Gahrns, M., "IMAP4 Multi-Accessed Mailbox Practice", RFC 2180, July 1997.
A.1 Informative References
these docs cover related protocols, so they're great for going deeper ๐ฆ
- [IMAP-DISC] Austein, R., "Synchronization Operations for Disconnected IMAP4 Clients", Work in Progress.
- [IMAP-MODEL] Crispin, M., "Distributed Electronic Mail Models in IMAP4", RFC 1733, December 1994.
- [ACAP] Newman, C. and J. Myers, "ACAP -- Application Configuration Access Protocol", RFC 2244, November 1997.
- [SMTP] Klensin, J., "Simple Mail Transfer Protocol", STD 10, RFC 2821, April 2001.
these ones are historical or describe historical aspects of this protocol, so think of them as the throwback playlist ๐ฐ๏ธ
- [IMAP-COMPAT] Crispin, M., "IMAP4 Compatibility with IMAP2bis", RFC 2061, December 1996.
- [IMAP-HISTORICAL] Crispin, M., "IMAP4 Compatibility with IMAP2 and IMAP2bis", RFC 1732, December 1994.
- [IMAP-OBSOLETE] Crispin, M., "Internet Message Access Protocol - Obsolete Syntax", RFC 2062, December 1996.
- [IMAP2] Crispin, M., "Interactive Mail Access Protocol - Version 2", RFC 1176, August 1990.
- [RFC-822] Crocker, D., "Standard for the Format of ARPA Internet Text Messages", STD 11, RFC 822, August 1982.
- [RFC-821] Postel, J., "Simple Mail Transfer Protocol", STD 10, RFC 821, August 1982.
B. Changes from RFC 2060
here's the tea on everything that changed since RFC 2060 โ it's a whole list, but every item is a little glow-up ๐
- Clarify description of unique identifiers and their semantics.
- Fix the SELECT description to clarify that
UIDVALIDITYis required in the SELECT and EXAMINE responses. - Added an example of a failing search.
- Correct store-att-flags:
#flagshould be1#flag. - Made search and section rules clearer.
- Correct the STORE example.
- Correct
BASE645misspelling. - Remove extraneous close parenthesis in example of two-part message with text and BASE64 attachment.
- Remove obsolete
MAILBOXresponse from mailbox-data. - A spurious
<in the rule for mailbox-data was removed. - Add CRLF to continue-req.
- Specifically exclude
]from the atom in resp-text-code. - Clarify that clients and servers should adhere strictly to the protocol syntax. strict syntax, strict vibes ๐โจ
- okay so in 5.2 we need to really emphasize that
EXISTScan not be used to shrink a mailbox ๐ฆ - add
NEWNAMEtoresp-text-codeโจ - clarify that the empty string, not
NIL, is what gets used as the arguments toLIST๐ง - clarify that
NILcan be returned as a hierarchy delimiter for the empty string mailbox name argument if the mailbox namespace is flat ๐ธ - clarify that
addr-mailboxandaddr-namehave RFC-2822 quoting removed ๐ - update the UTF-7 reference ๐ฆ
- fix the example in 6.3.11 ๐
- clarify that non-existent UIDs are ignored ๐
- update the DISPOSITION reference ๐
- expand the state diagram ๐ฅ
- clarify that partial fetch responses are only returned in response to a partial fetch command ๐
- add the UIDNEXT response code and correct the UIDVALIDITY definition reference ๐
- further clarification of "can" vs. MAY ๐ซถ
- reference RFC-2119 โจ
- clarify that superfluous shifts are not permitted in modified UTF-7 ๐
- clarify that there are no implicit shifts in modified UTF-7 ๐ท
- clarify that "INBOX" in a mailbox name is always INBOX, even if it is given as a string ๐
- add the missing open parenthesis in the
media-basicgrammar rule ๐ - correct the attribute syntax in
mailbox-data๐งฉ - add UIDNEXT to EXAMINE responses ๐ฆ
- clarify the UNSEEN, PERMANENTFLAGS, UIDVALIDITY, and UIDNEXT responses in SELECT and EXAMINE. they are required now, but weren't in older versions ๐
- update references with RFC numbers ๐
- flush
text-mime2๐งน - clarify that modified UTF-7 names must be case-sensitive and that violating the convention should be avoided ๐
- correct the UID FETCH example ๐
- clarify UID FETCH, UID STORE, and UID SEARCH vs. untagged EXPUNGE responses ๐ซง
- clarify the use of the word "convention" ๐
- clarify that a command is not "in progress" until it has been fully received (specifically, that a command is not "in progress" during command continuation negotiation) ๐ธ
- clarify envelope defaulting ๐
- clarify that
SPmeans one and only one space character โจ - forbid silly states in LIST response ๐
- clarify that the ENVELOPE, INTERNALDATE, RFC822*, BODY*, and UID for a message is static ๐
- add the BADCHARSET response code ๐
- update the formal syntax to [ABNF] conventions ๐
- clarify trailing hierarchy delimiter in CREATE semantics ๐๏ธ
- clarify that the "blank line" is the [RFC-2822] delimiting blank line ๐ซง
- clarify that RENAME should also create hierarchy as needed for the command to complete ๐๏ธ
- fix body-ext-mpart so it does not require language if disposition is present ๐
- clarify the RFC822.HEADER response ๐จ
- correct the missing space after charset astring in search ๐
- correct the missing quote for BADCHARSET in resp-text-code ๐ฉท
- clarify that ALL, FAST, and FULL preclude any other data items appearing ๐
- clarify semantics of the reference argument in LIST ๐งญ
- clarify that a null string for SEARCH HEADER X-FOO means any message with a header line with a field-name of X-FOO regardless of the text of the header ๐
- specifically reserve 8-bit mailbox names for future use as UTF-8 ๐
- it is not an error for the client to store a flag that is not in the PERMANENTFLAGS list. however, the server will either ignore the change or make the change in the session only ๐ซถ
- correct and clarify the text regarding superfluous shifts ๐ ๏ธ
- correct typographic errors in the "Changes" section โ๏ธ
- clarify that STATUS must not be used to check for new messages in the selected mailbox ๐ซ
- clarify LSUB behavior with the "%" wildcard ๐
- change AUTHORIZATION to AUTHENTICATE in section 7.5 ๐
- clarify description of the multipart body type ๐ง
- clarify that STORE FLAGS does not affect \Recent ๐ฆ
- change "west" to "east" in the description of timezone ๐งญ
- clarify that commands which break command pipelining must wait for a completion result response โณ
- clarify that EXAMINE does not affect \Recent ๐
- make the description of MIME structure consistent ๐
- clarify that date searches disregard the time and timezone of the INTERNALDATE or Date: header. in other words, "ON 13-APR-2000" means messages with an INTERNALDATE text which starts with "13-APR-2000", even if timezone differential from the local timezone is sufficient to move that INTERNALDATE into the previous or next day ๐
- clarify that the header fetches don't add a blank line if one isn't in the [RFC-2822] message ๐ซ
- clarify (in the discussion of UIDs) that messages are immutable ๐
- add an example of CHARSET searching ๐
- clarify in SEARCH that keywords are a type of flag ๐ท๏ธ
- clarify the mandatory nature of the SELECT data responses ๐
- add the optional CAPABILITY response code in the initial OK or PREAUTH ๐ซ
- add a note that the server can send an untagged CAPABILITY command as part of the responses to AUTHENTICATE and LOGIN ๐ฌ
- remove the statement about it being unnecessary to issue a CAPABILITY command more than once in a connection. that statement is no longer true ๐
- clarify that untagged EXPUNGE decrements the number of messages in the mailbox ๐
- fix the definition of "body" (concatenation has tighter binding than alternation) ๐ง
- add a new "Special Notes to Implementors" section with reference to [IMAP-IMPLEMENTATION] ๐
- clarify that an untagged CAPABILITY response to an AUTHENTICATE command should only be done if a security layer was not negotiated ๐ก๏ธ
- change the definition of atom to exclude "]". update astring to include "]" for compatibility with the past. remove resp-text-atom ๐งน
- remove NEWNAME. it can't work because mailbox names can be literals and can include "]". functionality can be addressed via referrals ๐ โโ๏ธ
- move the modified UTF-7 rationale so the paragraph flow makes more sense ๐
- clarify UID uniqueness guarantees with the use of MUST ๐
- note that clients should read response data until the connection is closed instead of immediately closing on a BYE ๐
- change RFC-822 references to RFC-2822 ๐ฎ
- clarify that RFC-2822 should be followed instead of RFC-822 ๐ฌ
- change the recommendation of optional automatic capabilities in LOGIN and AUTHENTICATE to use the CAPABILITY response code in the tagged OK. this is more interoperable than an unsolicited untagged CAPABILITY response ๐ค
- STARTTLS and AUTH=PLAIN are mandatory to implement. add recommendations for other [SASL] mechanisms ๐
- clarify that a "connection" (as opposed to "server" or "command") is in one of the four states ๐
- clarify that a failed or rejected command does not change state ๐ง
- split references between normative and informative ๐
- discuss authentication failure issues in the security section ๐จ
- clarify that a data item is not necessarily of only one data type ๐งฉ
- clarify that sequence ranges are independent of order ๐ข
- change an example to clarify that superfluous shifts in Modified-UTF7 can not be fixed just by omitting the shift. the entire string must be recalculated ๐งฎ
- change the Envelope Structure definition since [RFC-2822] uses "envelope" to refer to the [SMTP] envelope and not the envelope data that appears in the [RFC-2822] header ๐
- expand on RFC822.HEADER response data vs. BODY[HEADER] ๐
- clarify Logout state semantics and change the ASCII art ๐ช
- security changes to comply with IESG requirements ๐ก๏ธโจ
- add a definition for body URI ๐
- break the sequence range definition into three rules, with rewritten descriptions for each ๐ช
- move STARTTLS and LOGINDISABLED here from [IMAP-TLS] ๐
- add an IANA Considerations section ๐๏ธ
- clarify valid client assumptions for new message UIDs vs. UIDNEXT ๐
- clarify that changes to permanentflags affect concurrent sessions as well as subsequent sessions ๐ฏ
- clarify that the authenticated state can be entered by the CLOSE command ๐ช๐
- emphasize that SELECT and EXAMINE are the exceptions to the rule that a failing command does not change state ๐
- clarify that newly-appended messages have the Recent flag set ๐
- clarify that newly-copied messages SHOULD have the Recent flag set ๐๐ฉต
- clarify that UID commands always return the UID in FETCH responses ๐ซถ
C. Key Word Index ๐
Index ๐โจ
okay bestie, this is the index, aka the big cheat sheet of every keyword, command, response, flag, and search key in the whole spec, with the page where each one lives ๐ง use it like a map ๐บ๏ธ๐
+FLAGS <flag list> (store command data item) ............... 59
+FLAGS.SILENT <flag list> (store command data item) ........ 59
-FLAGS <flag list> (store command data item) ............... 59
-FLAGS.SILENT <flag list> (store command data item) ........ 59
ALERT (response code) ...................................... 64
ALL (fetch item) ........................................... 55
ALL (search key) ........................................... 50
ANSWERED (search key) ...................................... 50
APPEND (command) ........................................... 45
AUTHENTICATE (command) ..................................... 27
BAD (response) ............................................. 66
BADCHARSET (response code) ................................. 64
BCC <string> (search key) .................................. 51
BEFORE <date> (search key) ................................. 51
BODY (fetch item) .......................................... 55
BODY (fetch result) ........................................ 73
BODY <string> (search key) ................................. 51
BODY.PEEK[<section>]<<partial>> (fetch item) ............... 57
BODYSTRUCTURE (fetch item) ................................. 57
BODYSTRUCTURE (fetch result) ............................... 74
BODY[<section>]<<origin octet>> (fetch result) ............. 74
BODY[<section>]<<partial>> (fetch item) .................... 55
BYE (response) ............................................. 67
Body Structure (message attribute) ......................... 12
CAPABILITY (command) ....................................... 24
CAPABILITY (response code) ................................. 64
CAPABILITY (response) ...................................... 68
CC <string> (search key) ................................... 51
CHECK (command) ............................................ 47
CLOSE (command) ............................................ 48
COPY (command) ............................................. 59
CREATE (command) ........................................... 34
DELETE (command) ........................................... 35
DELETED (search key) ....................................... 51
DRAFT (search key) ......................................... 51
ENVELOPE (fetch item) ...................................... 57
ENVELOPE (fetch result) .................................... 77
EXAMINE (command) .......................................... 33
EXISTS (response) .......................................... 71
EXPUNGE (command) .......................................... 48
EXPUNGE (response) ......................................... 72
Envelope Structure (message attribute) ..................... 12
FAST (fetch item) .......................................... 55
FETCH (command) ............................................ 54
FETCH (response) ........................................... 73
FLAGGED (search key) ....................................... 51
FLAGS (fetch item) ......................................... 57
FLAGS (fetch result) ....................................... 78
FLAGS (response) ........................................... 71
FLAGS <flag list> (store command data item) ................ 59
FLAGS.SILENT <flag list> (store command data item) ......... 59
FROM <string> (search key) ................................. 51
FULL (fetch item) .......................................... 55
Flags (message attribute) .................................. 11
HEADER (part specifier) .................................... 55
HEADER <field-name> <string> (search key) .................. 51
HEADER.FIELDS <header-list> (part specifier) ............... 55
HEADER.FIELDS.NOT <header-list> (part specifier) ........... 55
INTERNALDATE (fetch item) .................................. 57
INTERNALDATE (fetch result) ................................ 78
Internal Date (message attribute) .......................... 12
KEYWORD <flag> (search key) ................................ 51
Keyword (type of flag) ..................................... 11
LARGER <n> (search key) .................................... 51
LIST (command) ............................................. 40
LIST (response) ............................................ 69
LOGIN (command) ............................................ 30
LOGOUT (command) ........................................... 25
LSUB (command) ............................................. 43
LSUB (response) ............................................ 70
MAY (specification requirement term) ....................... 4
MESSAGES (status item) ..................................... 45
MIME (part specifier) ...................................... 56
MUST (specification requirement term) ...................... 4
MUST NOT (specification requirement term) .................. 4
Message Sequence Number (message attribute) ................ 10
NEW (search key) ........................................... 51
NO (response) .............................................. 66
NOOP (command) ............................................. 25
NOT <search-key> (search key) .............................. 52
OK (response) .............................................. 65
OLD (search key) ........................................... 52
ON <date> (search key) ..................................... 52
OPTIONAL (specification requirement term) .................. 4
OR <search-key1> <search-key2> (search key) ................ 52
PARSE (response code) ...................................... 64
PERMANENTFLAGS (response code) ............................. 64
PREAUTH (response) ......................................... 67
Permanent Flag (class of flag) ............................. 12
READ-ONLY (response code) .................................. 65
READ-WRITE (response code) ................................. 65
RECENT (response) .......................................... 72
RECENT (search key) ........................................ 52
RECENT (status item) ....................................... 45
RENAME (command) ........................................... 37
REQUIRED (specification requirement term) .................. 4
RFC822 (fetch item) ........................................ 57
RFC822 (fetch result) ...................................... 78
RFC822.HEADER (fetch item) ................................. 57
RFC822.HEADER (fetch result) ............................... 78
RFC822.SIZE (fetch item) ................................... 57
RFC822.SIZE (fetch result) ................................. 78
RFC822.TEXT (fetch item) ................................... 58
RFC822.TEXT (fetch result) ................................. 79
SEARCH (command) ........................................... 49
SEARCH (response) .......................................... 71
SEEN (search key) .......................................... 52
SELECT (command) ........................................... 31
SENTBEFORE <date> (search key) ............................. 52
SENTON <date> (search key) ................................. 52
SENTSINCE <date> (search key) .............................. 52
SHOULD (specification requirement term) .................... 4
SHOULD NOT (specification requirement term) ................ 4
SINCE <date> (search key) .................................. 52
SMALLER <n> (search key) ................................... 52
STARTTLS (command) ......................................... 27
STATUS (command) ........................................... 44
STATUS (response) .......................................... 70
STORE (command) ............................................ 58
SUBJECT <string> (search key) .............................. 53
SUBSCRIBE (command) ........................................ 38
Session Flag (class of flag) ............................... 12
System Flag (type of flag) ................................. 11
TEXT (part specifier) ...................................... 56
TEXT <string> (search key) ................................. 53
TO <string> (search key) ................................... 53
TRYCREATE (response code) .................................. 65
UID (command) .............................................. 60
UID (fetch item) ........................................... 58
UID (fetch result) ......................................... 79
UID <sequence set> (search key) ............................ 53
UIDNEXT (response code) .................................... 65
UIDNEXT (status item) ...................................... 45
UIDVALIDITY (response code) ................................ 65
UIDVALIDITY (status item) .................................. 45
UNANSWERED (search key) .................................... 53
UNDELETED (search key) ..................................... 53
UNDRAFT (search key) ....................................... 53
UNFLAGGED (search key) ..................................... 53
UNKEYWORD <flag> (search key) .............................. 53
UNSEEN (response code) ..................................... 65
UNSEEN (search key) ........................................ 53
UNSEEN (status item) ....................................... 45
UNSUBSCRIBE (command) ...................................... 39
Unique Identifier (UID) (message attribute) ................ 8
X<atom> (command) .......................................... 62
[RFC-2822] Size (message attribute) ........................ 12
\Answered (system flag) .................................... 11
\Deleted (system flag) ..................................... 11
\Draft (system flag) ....................................... 11
\Flagged (system flag) ..................................... 11
\Marked (mailbox name attribute) ........................... 69
\Noinferiors (mailbox name attribute) ...................... 69
\Noselect (mailbox name attribute) ......................... 69
\Recent (system flag) ...................................... 11
\Seen (system flag) ........................................ 11
\Unmarked (mailbox name attribute) ......................... 69
Author's Address ๐
okay and last but not least, the people who wrote this whole thing ๐ซถ here's how to reach the author ๐
Mark R. Crispin
Networks and Distributed Computing
University of Washington
4545 15th Avenue NE
Seattle, WA 98105-4527
Phone: (206) 543-5762
EMail: MRC@CAC.Washington.EDU
Full Copyright Statement
Okay so, the legal bit, but make it cute ๐. Copyright is (C) The Internet Society (2003). All Rights Reserved. ๐
You're allowed to copy this document and share it with others, and you can make derivative works that comment on it, explain it, or help people implement it. You can publish and distribute those too, in whole or in part, with no restrictions of any kind ๐ฆ. The only requirement is that the copyright notice and this paragraph stay on every copy and derivative work ๐.
Now the catch: you may not modify this document itself in any way. That means you can't remove the copyright notice or the references to the Internet Society or other Internet organizations โ. The exceptions are when you need it for developing Internet standards (then you follow the copyright procedures defined in the Internet Standards process ๐ฅ), or when you translate it into a language other than English ๐.
Also, these permissions are perpetual, and the Internet Society and its successors or assigns won't revoke them ๐. This document and everything in it is provided on an "AS IS" basis ๐ซถ. THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, including but not limited to any warranty that using the information here won't infringe any rights, and any implied warranties of merchantability or fitness for a particular purpose ๐ .
Translation: use it, share it, build cool stuff with it, just keep the notice on it and don't edit the original. Periodt ๐ธ
Acknowledgement
Funding for the RFC Editor function is currently provided by the Internet Society โจ. Thank you to the people keeping the lights on behind the scenes ๐ง
๐ฆ where this page comes from
- ietf: rfc3501 2003-03
- ๐ girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms