Reading Mail
IMAP by hand, and the two alternatives.
SMTP pushes a message towards a mailbox. Getting it out is a different protocol.
A server with mailboxes
MailHog has no IMAP, so this chapter uses GreenMail — SMTP 3025, IMAP 3143, POP3 3110:
docker run -d -p 3025:3025 -p 3143:3143 -p 3110:3110 \
greenmail/standalone:2.1.6Send it one message, as chapter 2 did:
printf '%s\r\n' 'EHLO t' 'MAIL FROM:<[email protected]>' \
'RCPT TO:<[email protected]>' 'DATA' 'From: [email protected]' \
'Subject: Hello IMAP' '' 'The body.' '.' 'QUIT' \
| nc -w 3 localhost 3025GreenMail accepts any password, so LOGIN [email protected] pw works. A real server would
want TLS first — chapter 6.
The shape of IMAP
Every command carries a tag you choose. Untagged lines come first, then one tagged line saying the command finished:
a1 LOGIN [email protected] pw
a2 LOGOUTa1 and a2 are mine. A client sends several at once and matches replies by tag.
SELECT
Opening a mailbox makes the server volunteer everything it knows:
a1 LOGIN [email protected] pw
a2 SELECT INBOX
a3 LOGOUT1 EXISTS is the message count. Two lines are filtered above because they do not repeat:
RECENT and UNSEEN mean “since you last looked”.
Folders live on the server, so every client sees the same ones:
a1 LOGIN [email protected] pw
a2 LIST "" "*"
a3 LOGOUTFETCH
Ask for exactly what you need — headers only, by name:
a1 LOGIN [email protected] pw
a2 SELECT INBOX
a3 FETCH 1 (BODY[HEADER.FIELDS (SUBJECT FROM)])
a4 LOGOUTA client lists an inbox by fetching subjects and sizes, downloading a body only when you open it.
Literals
{42} is not part of the headers — it says the next 42 bytes are data, which may contain
anything including newlines.
A line-based parser breaks here. After reading {42} a client must switch to counting
bytes, which is why IMAP clients are harder to write than SMTP clients.
Flags
Flags are stored per message, and setting one is a command:
a1 LOGIN [email protected] pw
a2 SELECT INBOX
a3 STORE 1 +FLAGS (\Deleted)
a4 LOGOUTThe message is still there. \Deleted is a mark; nothing goes until EXPUNGE.
SEARCH
The server does the work and returns message numbers:
a1 LOGIN [email protected] pw
a2 SELECT INBOX
a3 SEARCH SUBJECT "IMAP"
a4 LOGOUTSearching server-side is the other reason IMAP exists: 50,000 messages searched without downloading any.
POP3
Ten commands, no folders, no flags, no search:
USER [email protected]
PASS pw
STAT
QUIT+OK 1 9 is one message of nine bytes. RETR 1 downloads it, DELE 1 removes it — the
mailbox is a queue.
| POP3 | IMAP | |
|---|---|---|
| State lives | on the device | on the server |
| Folders | none | server-side |
| Two devices | each sees different mail | both see the same |
| Protocol size | ten commands | dozens |
POP3 is not obsolete, it is narrow — simpler for one device archiving locally, wrong for anything else.
JMAP
JSON over HTTP, designed to replace both. One request fetches mailboxes, a message list and the messages, where IMAP needs a round trip each.