Day 1 · How email works
SMTP explained: commands, reply codes, STARTTLS and bounces
Course contents
SMTP is a conversation in plain text: the client sends a command, the server answers with a three-digit code and a sentence. It is simple enough to type by hand, and that’s exactly what you’ll do in this lesson, against a real Postfix server. Once you have seen a session with your own eyes, every log line, bounce message and error code in the rest of the course will make sense.
Set up the lab server
The labs from here on use a small mail server on your Linux machine: Postfix for SMTP, Dovecot for IMAP and for checking passwords, two users (alice and bob), and a fake “remote” MX for example.net written in Python. Everything listens on 127.0.0.1 only. Run this once; lesson 6 explains every setting.
#!/usr/bin/env bash
# mail-lab-setup.sh: run as root on a disposable Debian/Ubuntu machine or VM
set -euo pipefail
# a TLS certificate for mail.example.com (self-signed; a real server uses Let's Encrypt)
grep -q mail.example.com /etc/hosts || echo "127.0.0.1 mail.example.com" >> /etc/hosts
mkdir -p /etc/ssl/lab && cd /etc/ssl/lab
openssl req -x509 -newkey rsa:2048 -nodes -keyout mail.key -out mail.crt -days 365 \
-subj "/CN=mail.example.com" -addext "subjectAltName=DNS:mail.example.com"
chmod 600 mail.key
# Postfix: receive mail for example.com on port 25, accept submissions on 587 and 465
postconf -e "myhostname = mail.example.com" "mydomain = example.com" "myorigin = \$mydomain" \
"mydestination = \$myhostname, \$mydomain, localhost" "inet_interfaces = loopback-only" \
"inet_protocols = ipv4" "mynetworks = 127.0.0.1/32" "home_mailbox = Maildir/" \
"maillog_file = /var/log/postfix.log" "smtpd_banner = \$myhostname ESMTP" \
"smtpd_tls_cert_file = /etc/ssl/lab/mail.crt" "smtpd_tls_key_file = /etc/ssl/lab/mail.key" \
"smtpd_tls_security_level = may" "smtpd_sasl_type = dovecot" "smtpd_sasl_path = private/auth"
postconf -M submission/inet="submission inet n - y - - smtpd"
postconf -P "submission/inet/syslog_name=postfix/submission" \
"submission/inet/smtpd_tls_security_level=encrypt" "submission/inet/smtpd_sasl_auth_enable=yes" \
"submission/inet/smtpd_recipient_restrictions=permit_sasl_authenticated,reject" \
"submission/inet/smtpd_relay_restrictions=permit_sasl_authenticated,reject"
postconf -M submissions/inet="submissions inet n - y - - smtpd"
postconf -P "submissions/inet/syslog_name=postfix/submissions" "submissions/inet/smtpd_tls_wrappermode=yes" \
"submissions/inet/smtpd_sasl_auth_enable=yes" \
"submissions/inet/smtpd_recipient_restrictions=permit_sasl_authenticated,reject" \
"submissions/inet/smtpd_relay_restrictions=permit_sasl_authenticated,reject"
# mail for example.net goes to the fake remote MX on port 2526 (instead of an MX lookup)
echo "example.net smtp:[127.0.0.1]:2526" > /etc/postfix/transport
postmap /etc/postfix/transport
postconf -e "transport_maps = hash:/etc/postfix/transport"
# Dovecot: IMAP and POP3 over TLS, Maildir in each home, and password checks for Postfix
cat > /etc/dovecot/local.conf <<'EOF'
protocols = imap pop3
listen = 127.0.0.1
mail_location = maildir:~/Maildir
ssl = required
ssl_cert = </etc/ssl/lab/mail.crt
ssl_key = </etc/ssl/lab/mail.key
auth_mechanisms = plain login
log_path = /var/log/dovecot.log
service auth {
unix_listener /var/spool/postfix/private/auth {
mode = 0660
user = postfix
group = postfix
}
}
EOF
# two mailbox users
for u in alice bob; do id "$u" >/dev/null 2>&1 || useradd -m -s /bin/bash "$u"; done
echo 'alice:alice-lab-pass' | chpasswd
echo 'bob:bob-lab-pass' | chpasswd
systemctl restart postfix dovecot # in a container without systemd: postfix start; dovecot
And the fake remote MX. It accepts mail for most addresses, but rejects any recipient whose name starts with nosuch and temporarily refuses (greylists) any that starts with grey, the way real servers do:
# fake_mx.py: run with ~/mail-lab/bin/python fake_mx.py (needs aiosmtpd from the course setup)
import threading
from aiosmtpd.controller import Controller
class Handler:
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
local = address.split("@")[0]
if local.startswith("nosuch"):
return "550 5.1.1 <%s>: Recipient address rejected: User unknown" % address
if local.startswith("grey"):
return "451 4.7.1 <%s>: Recipient address rejected: Greylisted, try again later" % address
envelope.rcpt_tos.append(address)
return "250 2.1.5 OK"
async def handle_DATA(self, server, session, envelope):
print(f"accepted from {envelope.mail_from} for {envelope.rcpt_tos}, {len(envelope.content)} bytes", flush=True)
return "250 2.0.0 OK: queued"
controller = Controller(Handler(), hostname="127.0.0.1", port=2526, server_hostname="mx.example.net")
controller.start()
print("fake MX for example.net listening on 127.0.0.1:2526", flush=True)
threading.Event().wait() # the controller runs in its own thread
A session, typed by hand
Connect to port 25 with nc -C (the -C sends the CRLF line endings SMTP requires) and type the client’s lines. Below, C: marks what you type and S: what the server answers; this is a real session against the lab server.
nc -C 127.0.0.1 25
S: 220 mail.example.com ESMTP
C: EHLO client.example.org
S: 250-mail.example.com
S: 250-PIPELINING
S: 250-SIZE 10240000
S: 250-VRFY
S: 250-ETRN
S: 250-STARTTLS
S: 250-ENHANCEDSTATUSCODES
S: 250-8BITMIME
S: 250-DSN
S: 250-SMTPUTF8
S: 250 CHUNKING
C: MAIL FROM:<sender@example.org>
S: 250 2.1.0 Ok
C: RCPT TO:<alice@example.com>
S: 250 2.1.5 Ok
C: RCPT TO:<carol@example.com>
S: 550 5.1.1 <carol@example.com>: Recipient address rejected: User unknown in local recipient table
C: DATA
S: 354 End data with <CR><LF>.<CR><LF>
C: From: Sender <sender@example.org>
C: To: Alice <alice@example.com>
C: Subject: Hello over raw SMTP
C: Date: Sun, 01 Nov 2026 09:14:02 +0000
C: Message-ID: <lab-1@example.org>
C:
C: Hi Alice, this message was typed by hand.
C: .
S: 250 2.0.0 Ok: queued as 730EE8A21F
C: QUIT
S: 221 2.0.0 Bye
Step by step:
- Greeting. The server speaks first, with
220and its name. A server that is overloaded or refuses you can answer421or554right here. EHLO name(“extended hello”) introduces the client by its host name and asks for the server’s extensions. Each line of the answer except the last has a-after the code; the last has a space. (HELOis the old command without extensions.) The name you give matters: receivers check that a server’s HELO name is a real host name, ideally the same as its reverse DNS.MAIL FROM:<address>starts a transaction and sets the envelope sender, where bounces will go.RCPT TO:<address>, once per recipient. Each recipient is accepted or refused on its own:aliceexists,caroldoesn’t (550 5.1.1), and the transaction continues for the recipients that were accepted.DATAand the354reply: from here, everything you send is the message itself, headers, empty line, body. A line containing only a dot ends the message. (If a line of the message itself starts with a dot, the client doubles it,.., and the server removes one: this is called dot-stuffing.)250 ... queued as 730EE8A21F: the most important line of the session. The server has written the message to disk and taken responsibility for it. The queue ID is how you find the message in the server’s logs.QUIT, or anotherMAIL FROMto send another message on the same connection.
Other commands you may meet: RSET (abort the current transaction), NOOP (keep-alive), VRFY and EXPN (ask whether an address or a list exists; disable them on public servers, because they help spammers harvest addresses), STARTTLS, AUTH and BDAT (below).
Extensions (ESMTP)
The EHLO answer lists what the server supports. The ones worth knowing:
| Extension | RFC | Meaning |
|---|---|---|
SIZE 10240000 | 1870 | Largest message accepted, in bytes. A client can announce the size in MAIL FROM:<...> SIZE=... and get refused before sending it |
PIPELINING | 2920 | The client may send several commands without waiting for each reply, saving round trips |
8BITMIME | 6152 | 8-bit bodies allowed without encoding |
SMTPUTF8 | 6531 | UTF-8 in addresses and headers |
STARTTLS | 3207 | Upgrade this connection to TLS |
AUTH PLAIN LOGIN | 4954 | Login methods (offered by this server only after TLS) |
ENHANCEDSTATUSCODES | 2034 | Replies carry an extra x.y.z status code |
DSN | 3461 | The client can ask for delivery notifications (NOTIFY=SUCCESS,FAILURE) |
CHUNKING | 3030 | BDAT sends the message in chunks of a known size instead of DATA, with no dot-stuffing |
REQUIRETLS | 8689 | Ask every hop to refuse to relay this message without TLS (rarely supported yet) |
Reply codes
Every reply starts with a three-digit code, and the first digit is what software acts on:
| First digit | Meaning | What the client does |
|---|---|---|
| 2xx | Success | Continue |
| 3xx | Go on, send more (only 354 after DATA, and 334 during AUTH) | Send the data |
| 4xx | Temporary failure | Keep the message, retry later |
| 5xx | Permanent failure | Stop, bounce to the sender |
With ENHANCEDSTATUSCODES (RFC 3463), a reply also carries a class.subject.detail code, which is far more specific: 5.1.1 is “bad destination mailbox”, 4.7.1 is “delivery not authorized, try later”. The first number repeats the class (2, 4 or 5), the second is the subject (1 address, 2 mailbox, 3 mail system, 4 network and routing, 5 protocol, 6 content, 7 security and policy).
| Reply | Meaning |
|---|---|
220 | Service ready (greeting, or ready for TLS) |
221 | Closing the connection |
235 2.7.0 | Authentication successful |
250 | OK |
354 | Start the message, end with a lone dot |
421 4.7.0 | Service not available, closing (too many connections, rate limited, shutting down) |
450 / 451 | Mailbox busy, local error, greylisting: try again |
452 4.2.2 | Mailbox full, temporarily |
454 4.7.1 | TLS or relay temporarily not available (Postfix uses it for “Relay access denied” by default) |
530 5.7.0 | Authentication or STARTTLS required first |
535 5.7.8 | Wrong user name or password |
550 5.1.1 | No such user |
550 5.7.1 | Refused by policy: spam, blocklist, not authorized |
552 5.3.4 | Message too big |
554 5.7.1 | Transaction failed, often “Relay access denied” or a blocklist |
Each big provider adds its own details to the text, and lesson 14 has a table of the ones from Gmail and Microsoft that you will see most.
Submission: STARTTLS and AUTH
Submission on port 587 starts in plaintext, just like port 25. The client must upgrade the connection with STARTTLS before it may log in. Try to authenticate first, and the lab server refuses (it doesn’t even advertise AUTH before TLS):
S: 220 mail.example.com ESMTP
C: EHLO laptop.example.com
S: 250-mail.example.com
S: 250-PIPELINING
...
S: 250-STARTTLS
...
C: AUTH PLAIN AGFsaWNlAGFsaWNlLWxhYi1wYXNz
S: 530 5.7.0 Must issue a STARTTLS command first
That AUTH PLAIN string is not encrypted at all, only base64-encoded: \0username\0password. Anyone who sees it has the password, which is why AUTH must only ever happen inside TLS:
printf '\0alice\0alice-lab-pass' | base64
echo 'AGFsaWNlAGFsaWNlLWxhYi1wYXNz' | base64 -d | tr '\0' '|'; echo
AGFsaWNlAGFsaWNlLWxhYi1wYXNz
|alice|alice-lab-pass
openssl s_client can do the STARTTLS step for you and then lets you type inside the encrypted connection:
openssl s_client -connect 127.0.0.1:587 -starttls smtp -crlf -quiet
depth=0 CN = mail.example.com
verify error:num=18:self-signed certificate
verify return:1
depth=0 CN = mail.example.com
verify return:1
250 CHUNKING
EHLO laptop.example.com
250-mail.example.com
250-PIPELINING
250-SIZE 10240000
250-VRFY
250-ETRN
250-AUTH PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250-DSN
250-SMTPUTF8
250 CHUNKING
AUTH PLAIN AGFsaWNlAGFsaWNlLWxhYi1wYXNz
235 2.7.0 Authentication successful
QUIT
221 2.0.0 Bye
After TLS, AUTH PLAIN LOGIN appears in the list and the login succeeds (235). The certificate warning is expected in the lab, where the certificate is self-signed; on a real server, verification must succeed. Port 465 works the same, but the TLS handshake happens immediately on connect, with no STARTTLS step (openssl s_client -connect host:465).
Modern providers increasingly refuse plain passwords even inside TLS: Google and Microsoft want OAuth 2.0 (AUTH XOAUTH2 or OAUTHBEARER) from mail apps, or an app-specific password where it’s still allowed. More on that in the next lesson.
Bounces, the null sender and backscatter
- Bounces and other automatic notifications are sent with an empty envelope sender,
MAIL FROM:<>, so that a bounce can never cause another bounce. Servers must accept<>as a sender; rejecting it breaks bounce delivery. - A server should reject a bad recipient during the SMTP session (with a 550 to
RCPT TO), as the lab server did forcarol. Then the sending server writes the bounce, to the real sender. - A server that accepts first and bounces later sends the bounce to whatever address was in
MAIL FROM. When spammers forge that address, thousands of bounces land in an innocent person’s inbox. This is backscatter, and servers that produce it end up on blocklists. Check recipients, spam and viruses before you say250toDATA. - Out-of-office replies have the same problem. Good auto-responders reply only once per sender per period, never to
<>, never to mailing lists (List-Id,Precedence: bulk) and never to other auto-replies (Auto-Submitted).
Relaying and the open relay
Relaying means accepting a message for a domain that isn’t yours and passing it on. A server must relay only for its own users: clients that logged in (SASL authentication) or trusted internal IP addresses. A server that relays for anyone is an open relay, and spammers find open relays within hours. In the 1990s most servers were open relays; today an open relay is blocklisted almost immediately.
Test it on the lab server from an address that isn’t trusted (127.0.0.2, which isn’t in mynetworks):
nc -s 127.0.0.2 -C 127.0.0.1 25
S: 220 mail.example.com ESMTP
C: EHLO spammer.example
...
C: MAIL FROM:<anyone@example.org>
S: 250 2.1.0 Ok
C: RCPT TO:<victim@gmail.com>
S: 454 4.7.1 <victim@gmail.com>: Relay access denied
C: RCPT TO:<alice@example.com>
S: 250 2.1.5 Ok
Mail for a foreign domain is refused; mail for the server’s own user is accepted. That is exactly the behavior every MX needs. (Postfix answers with a temporary 454 by default, so that a configuration mistake delays mail instead of losing it; many admins switch to a permanent 554 once they’re sure.)
LMTP: SMTP for the last step
Between an MTA and the mailbox server on the same site, the usual protocol is LMTP (RFC 2033), a variant of SMTP without a queue: the mailbox server answers per recipient, immediately, whether it stored the message. Postfix delivering into Dovecot over LMTP is the standard design for a modern self-hosted server. LMTP must never be exposed to the Internet.