SMTP dialog

SMTP is a text-based TCP protocol that works on port 25. SMTP works in a lock-step, one-at-a-time dialog, with the client sending commands and the server sending responses for each command.

In a typical session, the dialog goes as follows:

  1. The client first establishes a connection to the SMTP server.
  2. The server initiates with a greeting. This greeting indicates that the server is ready to receive commands.
  3. The client then issues its own greeting.
  4. The server responds.
  5. The client sends a command indicating who the mail is from.
  6. The server responds to indicate that the sender is accepted.
  7. The client issues another command, which specifies the mail's recipient.
  8. The server responds indicating the recipient is accepted.
  9. The client then issues a DATA command.
  10. The server responds asking the client to proceed.
  11. The client transfers the email.

The protocol is very simple. In the following example SMTP session, mail.example.net is the client, and the server is mail.example.com (C and S indicate whether the client or server is sending, respectively):

S: 220 mail.example.com SMTP server ready
C: HELO mail.example.net
S: 250 Hello mail.example.net [192.0.2.67]
C: MAIL FROM:<alice@example.net>
S: 250 OK
C: RCPT TO:<bob@example.com>
S: 250 Accepted
C: DATA
S: 354 Enter message, ending with "." on a line by itself
C: Subject: Re: The Cake
C: Date: Fri, 03 May 2019 02:31:20 +0000
C:
C: Do NOT forget to bring the cake!
C: .
S: 250 OK
C: QUIT
S: 221 closing connection

Everything the server sends is in reply to the client's commands, except for the first line. The first line is simply in response to the client connecting.

You may notice that each of the client's commands start with a four-letter word. Each one of the server's responses starts with a three-digit code.

The common client commands we use are as follows:

The server response codes used in a successful email transfer are the following:

Error codes vary between providers, but they are generally in the 500 range.

SMTP servers can also send replies spanning multiple lines. In this case, the very last line begins with the response code followed by a space. All preceding lines begin with the response code followed by a dash. The following example illustrates a multiline response after attempting to deliver to a mailbox that does not exist:

C: MAIL FROM:<alice@example.net>
S: 250 OK
C: RCPT TO:<not-a-real-user@example.com>
S: 550-The account you tried to deliver to does not
S: 550-exist. Please double-check the recipient's
S: 550 address for typos and try again.

Note that some servers validate that the recipient address is valid before replying to the RCPT command, but many servers only validate the recipient address after the client sends the email using the DATA command.

Although that explains the basics of the protocol used to send mail, we still must consider the format of the email itself. This is covered next.