Foundations of Python Network Programming

(WallPaper) #1

Chapter 14 ■ pOp


260


Connecting and Authenticating


POP supports several authentication methods. The two most common are basic username-password authentication
and APOP, which is an optional extension to POP that helps protect passwords from being sent in plain text if you are
using an ancient POP server that does not support SSL.
The process of connecting and authenticating to a remote server looks like this in Python:



  1. Create a POP3_SSL or just a plain POP3 object, and pass the remote hostname and port to it.

  2. Call user() and pass() to send the username and password. Note the underscore in
    pass
    ()! It is present because pass is a keyword in Python and cannot be used for a
    method name.

  3. If the exception poplib.error_proto is raised, it means that the login has failed and the
    string value of the exception contains the error explanation sent by the server.


The choice between POP3 and POP3_SSL is governed by whether your e-mail provider offers—or, in this day and
age, even requires—that you connect over an encrypted connection. Consult Chapter 6 for more information about
SSL, but the general rule should be to use SSL whenever it is at all feasible to do so.
Listing 14-1 uses the foregoing steps to log in to a remote POP server. Once connected, it calls stat(), which
returns a simple tuple giving the number of messages in the mailbox and the messages’ total size. Finally, the program
calls quit(), which closes the POP connection.


Figure 14-1. A simple conversation using POP

Free download pdf