Learning Python Network Programming

(Sean Pound) #1
Chapter 4

Retrieving e-mails by using POP3 with poplib


The stored e-mail messages can be downloaded and read by the local computer.
The POP3 protocol can be used to download the messages from the e-mail server.
Python has a module called poplib, and it can be used for this purpose. This module
provides two high-level classes, POP() and POP3_SSL(),which implement the POP3
and POP3S protocols respectively for communicating with a POP3/POP3S server.
It accepts three arguments, host, port, and timeout. If port is omitted, then the
default port (110) can be used. The optional timeout parameter determines the
length (in seconds) of the connection timeout at the server.


The secure version of POP3() is its subclass POP3_SSL(). It takes additional
parameters, such as keyfile and certfile, which are used for supplying the SSL
certificate files, namely the private key and certificate chain file.


Writing for a POP3 client is also very straightforward. To do this, instantiate a mailbox
object by initializing the POP3() or POP3SSL() class. Then, invoke the user() and
pass
() methods to login to the server by using the following command:


mailbox = poplib.POP3_SSL(<POP3_SERVER>, <SERVER_PORT>)
mailbox.user('username')
mailbox.pass_('password')

Now, you can call the various methods for manipulating your accounts and
messages. A few interesting methods have been listed here:



  • stat(): This method returns the mailbox status according to tuples
    of two integers, that is, the message count and the size of the mailbox.

  • list(): This method sends a request for getting a message list,
    which has been demonstrated in the example shown later in this section.

  • retr(): This method gives an argument message a number
    that indicates the message that has to be retrieved. It also marks the
    message as read.

  • dele(): This method provides an argument for the message that has to be
    deleted. On many POP3 servers, the deletion is not performed until QUIT.
    You can reset the delete flag by using the rset() method.

  • quit(): This method takes you off the connection by committing a few
    changes and disconnecting you from the server.

Free download pdf