Chapter 14 ■ pOp
262
This program takes two command-line arguments: the hostname of your POP server, and your username. If you do
not know this information, contact your Internet provider or network administrator. Note that on some services, your
username will be a plain string (like guido), whereas on others it will be your full e-mail address ([email protected]).
The program will then prompt you for your password. Finally, it will display the mailbox status, without touching
or altering any of your mail.
Here is how you might run the program inside of the Mininet playground, which you can download from the
book’s source repository (see Chapter 1):
$ python3 popconn.py mail.example.com brandon
Password: abc123
You have 3 messages totaling 5675 bytes
If you see output like this, then your first POP conversation has taken place successfully!
When POP servers do not support SSL to protect your connection from snooping, they sometimes at least
support an alternate authentication protocol called APOP, which uses a challenge–response scheme to ensure that
your password is not sent in the clear. (However, all of your e-mail will still be visible to any third party watching the
packets go by!) The Python Standard Library makes this very easy to attempt: just call the apop() method, then fall
back to basic authentication if the POP server to which you are talking does not understand.
To use APOP but fall back to plain authentication, you could use a stanza like the one shown in Listing 14-2 inside
your POP program (like Listing 14-1).
Listing 14-2. Attempting APOP and Falling Back
print("Attempting APOP authentication...")
try:
p.apop(user, passwd)
except poplib.errorproto:
print("Attempting standard authentication...")
try:
p.user(user)
p.pass(passwd)
except poplib.error_proto as e:
print("Login failed:", e)
sys.exit(1)
■ Caution as soon as a login succeeds by whatever method, some older pOp servers will lock the mailbox. Locking
might mean that no alterations to the mailbox may be made, or even that no more e-mail may be delivered until the lock
is gone. the problem is that some pOp servers do not properly detect errors, and they will keep a box locked indefinitely if
your connection gets hung up without your calling quit(). at one time, the world’s most popular pOp server fell into this
category! thus it is vital to always call quit() in your python programs when finishing up a pOp session. You will note
that all of the program listings shown here are always careful to quit() down in a finally block that python is guaran-
teed to execute last.