Foundations of Python Network Programming

(WallPaper) #1

Chapter 14 ■ pOp


264


The three strings inside the second item give the message number and size for each of the three messages in my
inbox. The simple parsing performed by Listing 14-3 lets it present the output in a prettier format. Here is how you
might run it against the POP server deployed inside of the book’s network playground (see Chapter 1):


$ python3 mailbox.py mail.example.com brandon
Password: abc123
Message 1 has 354 bytes
Message 2 has 442 bytes
Message 3 has 1173 bytes


Downloading and Deleting Messages


You should now be getting the hang of POP: when using poplib, you issue small atomic commands that always return
a tuple, inside of which are various strings and lists of strings that show you the results. You are now actually ready to
manipulate messages! The three relevant methods, which all identify messages using the same integer identifiers that
are returned by list(), are as follows:


•    retr(num): This method downloads a single message and returns a tuple containing a result
code and the message itself, delivered as a list of lines. This will cause most POP servers to
set the “seen” flag for the message to “true,” barring you from ever seeing it from POP again
(unless you have another way into your mailbox that lets you set messages back to “Unread”).

•    top(num, body_lines): This method returns its result in the same format as retr() without
marking the message as “seen.” But instead of returning the whole message, it just returns
the headers plus however many lines of the body you ask for in body_lines. This is useful for
previewing messages if you want to let the user decide which ones to download.

•    dele(num): This method marks the message for deletion from the POP server, to take place
when you quit this POP session. Typically, you would do this only if the user directly requests
irrevocable destruction of the message or if you have stored the message to redundant storage
(and perhaps backed it up) and have used something like fsync() to ensure that the data have
really been written, because you will never again be able to retrieve the message from the server.

To put everything together, take a look at Listing 14-4, which is a fairly functional e-mail client that speaks POP!
It checks your in box to determine how many messages there are and to learn their numbers; then it uses top() to
offer a preview of each one; and, at the user’s option, it can retrieve the whole message and delete it from the mailbox.


Listing 14-4. A Simple POP E-mail Reader


#!/usr/bin/env python3


Foundations of Python Network Programming, Third Edition


https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter14/download-and-delete.py


import email, getpass, poplib, sys


def main():
if len(sys.argv) != 3:
print('usage: %s hostname username' % sys.argv[0])
exit(2)

Free download pdf