Chapter 13 ■ SMtp
251
reply: b'250 HELP\r\n'
reply: retcode (250); Msg: b'guinness\nSIZE 33554432\nHELP'
send: 'mail FROM:[email protected] size=212\r\n'
reply: b'250 OK\r\n'
reply: retcode (250); Msg: b'OK'
send: 'rcpt TO:[email protected]\r\n'
reply: b'250 OK\r\n'
reply: retcode (250); Msg: b'OK'
send: 'data\r\n'
reply: b'354 End data with
reply: retcode (354); Msg: b'End data with
data: (354, b'End data with
send: b'To: [email protected]\r\nFrom: [email protected]\r\nSubject: Test Message from
simple.py\r\n\r\nHello,\r\n\r\nThis is a test message sent to you from the debug.py program\r\nin
Foundations of Python Network Programming.\r\n.\r\n'
reply: b'250 OK\r\n'
reply: retcode (250); Msg: b'OK'
data: (250, b'OK')
send: 'quit\r\n'
reply: b'221 Bye\r\n'
reply: retcode (221); Msg: b'Bye'
Message sent to 1 recipient
From this example, you can see the conversation that smtplib is having with the SMTP server over the network.
As you implement code that uses more advanced SMTP features, the details shown here will be more important, so
let’s look at what’s happening.
First, the client (the smtplib library) sends an EHLO command (an “extended” successor to a more ancient
command that was named, more readably, HELO) with your hostname in it. The remote server responds with its own
hostname, and it lists any optional SMTP features that it supports.
Next, the client sends the mail from command, which states the “envelope sender” e-mail address and the size
of the message. The server at this moment has the opportunity to reject the message (for example, because it thinks
you are a spammer); but in this case it responds with 250 Ok. (Note that in this case, the code 250 is what matters; the
remaining text is just a human-readable comment and varies from server to server.)
Then the client sends a rcpt to command, with the “envelope recipient,” which I discussed previously in this chapter.
You can finally see that, indeed, it is transmitted separately from the text of the message itself when using the SMTP
protocol. If you were sending the message to more than one recipient, they would each be listed on the rcpt to line.
Finally, the client sends a data command, transmits the actual message (using verbose carriage-return-linefeed
line endings, you will note, per the Internet e-mail standard), and finishes the conversation.
The smtplib module is doing all of this automatically for you in this example. In the rest of the chapter, I’ll explain
how to take more control of the process to take advantage of some more advanced features.
■ Caution Don’t get a false sense of confidence that because no error was detected during this first hop, you’re
convinced that the message is now guaranteed to be delivered. In many cases, an e-mail server may accept a message,
only to have delivery fail at a later time. reread the “Multiple hops” section and imagine how many possibilities of failure
there are before that sample message reaches its destination!