Email Protocols
Email is one of the oldest Internet applications, and it still runs on protocols from the early 1980s, carefully extended. Three protocols do the work:
| Protocol | Port(s) | Job |
|---|---|---|
| SMTP | 25 (server to server), 587 (submission with STARTTLS), 465 (implicit TLS) | sending: from your client to your mail server, and between mail servers |
| IMAP | 143, 993 (TLS) | reading: mail stays on the server, folders sync across devices |
| POP3 | 110, 995 (TLS) | reading: download and (usually) delete from the server |
The journey of a message
- Your mail client (MUA) submits the message over SMTP (port 587, authenticated) to your provider's server.
- That server looks up the recipient domain's MX records in DNS to find its mail servers.
- It relays the message over SMTP (port 25) to the highest-priority (lowest number) MX that answers.
- The recipient's server stores it in their mailbox.
- The recipient's client fetches it with IMAP.
MX = {
"example.org": [(20, "backup-mx.example.org"), (10, "mx1.example.org"), (10, "mx2.example.org")],
}
REACHABLE = {"mx2.example.org", "backup-mx.example.org"}
def deliver(recipient):
domain = recipient.split("@", 1)[1]
for priority, host in sorted(MX[domain]):
status = "accepted" if host in REACHABLE else "connection timed out"
print(f" try MX {priority:>2} {host:<22} {status}")
if host in REACHABLE:
return host
print(" all MX hosts failed: queue the message and retry later")
print("deliver to lan@example.org")
deliver("lan@example.org")deliver to lan@example.org
try MX 10 mx1.example.org connection timed out
try MX 10 mx2.example.org accepted
MX records with the same priority share load; higher numbers are backups. If every server is down, the sending server queues the message and retries for days before bouncing it.
An SMTP dialogue
SMTP is a text protocol of commands and 3-digit reply codes, like HTTP's status codes (2xx success, 3xx "go on", 4xx temporary failure, 5xx permanent failure). Here's a simulated server that implements the core of RFC 5321, run against a client script:
class SmtpServer:
def __init__(self, domain, mailboxes):
self.domain, self.mailboxes = domain, mailboxes
self.state, self.sender, self.rcpts, self.data_lines = "start", None, [], []
def greet(self):
return f"220 {self.domain} ESMTP ready"
def handle(self, line):
if self.state == "data":
if line == ".":
self.state = "ready"
for r in self.rcpts:
self.mailboxes[r].append("\n".join(self.data_lines))
return f"250 OK: queued for {len(self.rcpts)} recipient(s)"
self.data_lines.append(line)
return None # no reply for message lines
verb = line.split(" ", 1)[0].upper()
if verb == "EHLO":
self.state = "ready"
return f"250-{self.domain} greets {line.split()[1]}\n250-SIZE 35882577\n250 STARTTLS"
if self.state == "start":
return "503 5.5.1 Send EHLO first"
if verb == "MAIL":
self.sender, self.rcpts = line[10:].strip("<>"), []
return "250 2.1.0 Sender OK"
if verb == "RCPT":
rcpt = line[8:].strip("<>")
if rcpt not in self.mailboxes:
return "550 5.1.1 No such user here"
self.rcpts.append(rcpt)
return "250 2.1.5 Recipient OK"
if verb == "DATA":
if not self.rcpts:
return "554 5.5.1 No valid recipients"
self.state, self.data_lines = "data", []
return "354 End data with <CR><LF>.<CR><LF>"
if verb == "QUIT":
return f"221 2.0.0 {self.domain} closing connection"
return "500 5.5.2 Command not recognized"
server = SmtpServer("mx2.example.org", {"lan@example.org": [], "minh@example.org": []})
script = ["EHLO mail.sender.example", "MAIL FROM:<an@sender.example>",
"RCPT TO:<lan@example.org>", "RCPT TO:<nobody@example.org>", "DATA",
"From: An <an@sender.example>", "To: Lan <lan@example.org>", "Subject: Lunch?", "",
"Pho at 12:30?", ".", "QUIT"]
print("S:", server.greet())
for line in script:
print("C:", line)
reply = server.handle(line)
if reply:
for r in reply.split("\n"):
print("S:", r)
print("lan's mailbox:", server.mailboxes["lan@example.org"])S: 220 mx2.example.org ESMTP ready
C: EHLO mail.sender.example
S: 250-mx2.example.org greets mail.sender.example
S: 250-SIZE 35882577
S: 250 STARTTLS
C: MAIL FROM:<an@sender.example>
S: 250 2.1.0 Sender OK
C: RCPT TO:<lan@example.org>
S: 250 2.1.5 Recipient OK
C: RCPT TO:<nobody@example.org>
S: 550 5.1.1 No such user here
C: DATA
S: 354 End data with <CR><LF>.<CR><LF>
C: From: An <an@sender.example>
C: To: Lan <lan@example.org>
C: Subject: Lunch?
C:
C: Pho at 12:30?
C: .
S: 250 OK: queued for 1 recipient(s)
C: QUIT
S: 221 2.0.0 mx2.example.org closing connection
lan's mailbox: ['From: An <an@sender.example>\nTo: Lan <lan@example.org>\nSubject: Lunch?\n\nPho at 12:30?']
Notice the envelope (MAIL FROM, RCPT TO) is separate from the headers (From:, To:) inside the message. The envelope decides delivery; the headers are just what the reader sees. That's why spammers could historically put any From: they liked.
Fighting spoofing: SPF, DKIM and DMARC
Three DNS-based mechanisms let receivers check that mail claiming to be from a domain really is:
| Mechanism | DNS record | Checks |
|---|---|---|
| SPF | TXT v=spf1 ... on the domain |
is the sending server's IP allowed to send for the envelope domain? |
| DKIM | TXT at selector._domainkey.domain (a public key) |
does the message's signature verify, proving the headers and body weren't altered? |
| DMARC | TXT at _dmarc.domain |
policy: what to do if SPF/DKIM fail or don't align with the From: domain |
import ipaddress
spf = "v=spf1 ip4:198.51.100.0/24 ip4:203.0.113.25 -all"
def check_spf(record, sender_ip):
ip = ipaddress.ip_address(sender_ip)
for term in record.split()[1:]:
if term.startswith("ip4:") and ip in ipaddress.ip_network(term[4:]):
return "pass"
if term in ("-all", "~all"):
return "fail" if term == "-all" else "softfail"
return "neutral"
for ip in ["198.51.100.77", "203.0.113.25", "192.0.2.66"]:
print(f"mail from {ip:<14} SPF {check_spf(spf, ip)}")mail from 198.51.100.77 SPF pass
mail from 203.0.113.25 SPF pass
mail from 192.0.2.66 SPF fail
dig +short TXT _dmarc.example.orgSample output:
"v=DMARC1; p=reject; rua=mailto:dmarc-reports@example.org"Reading mail: IMAP
IMAP is also a text protocol. Each command is tagged so replies can be matched, which lets a client send several commands without waiting:
C: a1 LOGIN lan@example.org app-password
S: a1 OK LOGIN completed
C: a2 SELECT INBOX
S: * 3 EXISTS
S: a2 OK [READ-WRITE] SELECT completed
C: a3 FETCH 3 (BODY[HEADER.FIELDS (FROM SUBJECT)])
S: * 3 FETCH (BODY[HEADER.FIELDS (FROM SUBJECT)] {50}
S: From: An <an@sender.example>
S: Subject: Lunch?
S: )
S: a3 OK FETCH completedTip: Test a mail server's SMTP by hand with
openssl s_client -starttls smtp -connect mail.example.org:587, then typeEHLO test. You'll see the same 250 replies as in the simulation above.
Test yourself
Which protocol sends mail between mail servers?
- IMAP
- POP3
- SMTP
- HTTP
A domain has MX records with priorities 10 and 20. Which server is tried first?
- The one with priority 20
- The one with priority 10
- Both at once
- A random one
What does an SMTP reply code starting with 4 mean?
- Success
- Send more data
- Temporary failure: try again later
- Permanent failure