poplib.rst 7.55 KB

:mod:`poplib` --- POP3 protocol client

Source code: :source:`Lib/poplib.py`


This module defines a class, :class:`POP3`, which encapsulates a connection to a POP3 server and implements the protocol as defined in RFC 1939. The :class:`POP3` class supports both the minimal and optional command sets from RFC 1939. The :class:`POP3` class also supports the STLS command introduced in RFC 2595 to enable encrypted communication on an already established connection.

Additionally, this module provides a class :class:`POP3_SSL`, which provides support for connecting to POP3 servers that use SSL as an underlying protocol layer.

Note that POP3, though widely supported, is obsolescent. The implementation quality of POP3 servers varies widely, and too many are quite poor. If your mailserver supports IMAP, you would be better off using the :class:`imaplib.IMAP4` class, as IMAP servers tend to be better implemented.

The :mod:`poplib` module provides two classes:

This class implements the actual POP3 protocol. The connection is created when the instance is initialized. If port is omitted, the standard POP3 port (110) is used. The optional timeout parameter specifies a timeout in seconds for the connection attempt (if not specified, the global default timeout setting will be used).

This is a subclass of :class:`POP3` that connects to the server over an SSL encrypted socket. If port is not specified, 995, the standard POP3-over-SSL port is used. timeout works as in the :class:`POP3` constructor. context is an optional :class:`ssl.SSLContext` object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read :ref:`ssl-security` for best practices.

keyfile and certfile are a legacy alternative to context - they can point to PEM-formatted private key and certificate chain files, respectively, for the SSL connection.

One exception is defined as an attribute of the :mod:`poplib` module:

POP3 Objects

All POP3 commands are represented by methods of the same name, in lower-case; most return the response text sent by the server.

An :class:`POP3` instance has the following methods:

Instances of :class:`POP3_SSL` have no additional methods. The interface of this subclass is identical to its parent.

POP3 Example

Here is a minimal example (without error checking) that opens a mailbox and retrieves and prints all messages:

import getpass, poplib

M = poplib.POP3('localhost')
M.user(getpass.getuser())
M.pass_(getpass.getpass())
numMessages = len(M.list()[1])
for i in range(numMessages):
    for j in M.retr(i+1)[1]:
        print(j)

At the end of the module, there is a test section that contains a more extensive example of usage.