09.11.2016 Views

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 14 ■ POP<br />

■ Caution! As soon as a login succeeds by whatever method, some older POP servers will lock the mailbox.<br />

Locking might mean that no alterations to the mailbox may be made, or even that no more mail may be delivered<br />

until the lock is gone. The problem is that some POP servers do not properly detect errors, and will keep a box<br />

locked indefinitely if your connection gets hung up without your calling quit(). At one time, the world’s most<br />

popular POP server fell into this category!<br />

So it is vital to always call quit() in your <strong>Python</strong> programs when finishing up a POP session. You will note that all<br />

<strong>of</strong> the program listings shown here are careful to always quit() down in a finally block that <strong>Python</strong> is<br />

guaranteed to execute last.<br />

Obtaining Mailbox Information<br />

The preceding example showed you stat(), which returns the number <strong>of</strong> messages in the mailbox and<br />

their total size. Another useful POP command is list(), which returns more detailed information about<br />

each message.<br />

The most interesting part is the message number, which is required to retrieve messages later. Note<br />

that there may be gaps in message numbers: a mailbox may, for example, contain message numbers 1, 2,<br />

5, 6, and 9. Also, the number assigned to a particular message may be different on each connection you<br />

make to the POP server.<br />

Listing 14–3 shows how to use the list() command to display information about each message.<br />

Listing 14–3. Using the POP list() Command<br />

#!/usr/bin/env python<br />

# POP mailbox scanning - Chapter 14 - mailbox.py<br />

import getpass, poplib, sys<br />

if len(sys.argv) != 3:<br />

» print 'usage: %s hostname user' % sys.argv[0]<br />

» exit(2)<br />

hostname, user = sys.argv[1:]<br />

passwd = getpass.getpass()<br />

p = poplib.POP3_SSL(hostname)<br />

try:<br />

» p.user(user)<br />

» p.pass_(passwd)<br />

except poplib.error_proto, e:<br />

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

else:<br />

» response, listings, octet_count = p.list()<br />

» for listing in listings:<br />

» » number, size = listing.split()<br />

» » print "Message %s has %s bytes" % (number, size)<br />

238

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

Saved successfully!

Ooh no, something went wrong!