Chapter 14 ■ pOp
263
Obtaining Mailbox Information
The preceding example showed you stat(), which returns the number of messages in the mailbox and their total size.
Another useful POP command is list(), which returns more detailed information about each message.
The most interesting part is the message number, which is required to retrieve messages later. Note that there
may be gaps in message numbers: at a given moment a mailbox may, for example, contain only message numbers 1,
2, 5, 6, and 9. Also, the number assigned to a particular message may be different on each connection that you make to
the POP server.
Listing 14-3 shows how to use the list() command to display information about each message.
Listing 14-3. Using the POP list() Command
#!/usr/bin/env python3
Foundations of Python Network Programming, Third Edition
https://github.com/brandon-rhodes/fopnp/blob/m/py3/chapter14/mailbox.py
import getpass, poplib, sys
def main():
if len(sys.argv) != 3:
print('usage: %s hostname username' % sys.argv[0])
exit(2)
hostname, username = sys.argv[1:]
passwd = getpass.getpass()
p = poplib.POP3SSL(hostname)
try:
p.user(username)
p.pass(passwd)
except poplib.error_proto as e:
print("Login failed:", e)
else:
response, listings, octet_count = p.list()
if not listings:
print("No messages")
for listing in listings:
number, size = listing.decode('ascii').split()
print("Message %s has %s bytes" % (number, size))
finally:
p.quit()
if name == 'main':
main()
The list() function returns a tuple containing three items. You should generally pay attention to the second
item. Here is the raw output for one of my POP mailboxes at the moment, which has three messages in it:
('+OK 3 messages (5675 bytes)', ['1 2395', '2 1626', '3 1654'], 24)