09.11.2016 Views

Foundations of Python Network Programming 978-1-4302-3004-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 14 ■ POP<br />

■ Caution! While this program does not alter any messages, some POP servers will nonetheless alter mailbox<br />

flags simply because you connected. Running the examples in this chapter against a live mailbox could cause you<br />

to lose information about which messages are read, unread, new, or old. Unfortunately, that behavior is serverdependent,<br />

and beyond the control <strong>of</strong> POP clients. I strongly recommend running these examples against a test<br />

mailbox rather than your live mailbox!<br />

Here is how you might run the program:<br />

$ ./popconn.py pop.example.com guido<br />

Password: (type your password)<br />

You have 3 messages totaling 5675 bytes<br />

If you see output like this, then your first POP conversation has taken place successfully!<br />

When POP servers do not support SSL to protect your connection from snooping, they sometimes at<br />

least support an alternate authentication protocol called APOP, which uses a challenge-response<br />

scheme to assure that your password is not sent in the clear. (But all <strong>of</strong> your e-mail will still be visible to<br />

any third party watching the packets go by!) The <strong>Python</strong> Standard Library makes this very easy to<br />

attempt: just call the apop() method, then fall back to basic authentication if the POP server you are<br />

talking to does not understand.<br />

To use APOP but fall back to plain authentication, you could use a stanza like the one shown in<br />

Listing 14–2 inside your POP program (like Listing 14–1).<br />

Listing 14–2. Attempting APOP and Falling Back<br />

print "Attempting APOP authentication..."<br />

try:<br />

» p.apop(user, passwd)<br />

except poplib.error_proto:<br />

» print "Attempting standard authentication..."<br />

» try:<br />

» » p.user(user)<br />

» » p.pass_(passwd)<br />

» except poplib.error_proto, e:<br />

» » print "Login failed:", e<br />

» » sys.exit(1)<br />

237

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!