IMAP Message Sequence Numbers Explained
In the IMAP (Internet Message Access Protocol) standard, a Message Sequence Number is a temporary, sequential integer used to identify a message within a specific mailbox.
Think of it as the current "row number" or "index" of an email in a list.
Here is a breakdown of how IMAP message sequence numbers work:
1. They are 1-based and contiguous
Sequence numbers always start at 1 for the oldest (or first) message in the mailbox and go up to N (where N is the total number of messages currently in the mailbox).
- There are never any gaps in sequence numbers.
- If a mailbox has 100 messages, they are numbered exactly 1 through 100.
2. They are highly volatile (They shift)
The most important characteristic of a sequence number is that it can change during a session. If a message is permanently removed (expunged) from the mailbox, the sequence numbers of all messages that came after it will immediately shift down by one to close the gap.
Example of shifting: Suppose your mailbox has 5 messages, numbered 1, 2, 3, 4, and 5.
- You delete and expunge message #3.
- Message #3 is gone.
- To prevent a gap, the server immediately renumbers the remaining messages.
- The old message #4 becomes the new #3.
- The old message #5 becomes the new #4.
3. Deletion vs. Expunging
It is important to note that simply marking a message as deleted (using the \Deleted flag) does not change sequence numbers. The message is still physically in the mailbox. The sequence numbers only shift when the client issues the EXPUNGE command (or the server auto-expunges), which permanently removes the flagged messages.
4. Sequence Numbers vs. UIDs
Because sequence numbers change so easily, IMAP uses a second type of identifier called a UID (Unique Identifier).
- Sequence Numbers: Temporary, have no gaps, change when emails are deleted. Good for relative requests (e.g., "Fetch messages 1 through 10" or "Fetch the last message, which is N").
- UIDs: Persistent, permanent ID numbers assigned to messages. They never change as long as the message is in that mailbox, but they do have gaps when messages are deleted (e.g., UIDs might be 100, 101, 105, 110).
When an email client interacts with an IMAP server, it often uses UIDs to keep track of a user's inbox locally, but it may use sequence numbers for quick bulk operations or when it first connects to count the total messages.