1:mod:`poplib` --- POP3 protocol client
2======================================
3
4.. module:: poplib
5   :synopsis: POP3 protocol client (requires sockets).
6
7.. sectionauthor:: Andrew T. Csillag
8.. revised by ESR, January 2000
9
10**Source code:** :source:`Lib/poplib.py`
11
12.. index:: pair: POP3; protocol
13
14--------------
15
16This module defines a class, :class:`POP3`, which encapsulates a connection to a
17POP3 server and implements the protocol as defined in :rfc:`1939`. The
18:class:`POP3` class supports both the minimal and optional command sets from
19:rfc:`1939`. The :class:`POP3` class also supports the ``STLS`` command introduced
20in :rfc:`2595` to enable encrypted communication on an already established connection.
21
22Additionally, this module provides a class :class:`POP3_SSL`, which provides
23support for connecting to POP3 servers that use SSL as an underlying protocol
24layer.
25
26Note that POP3, though widely supported, is obsolescent.  The implementation
27quality of POP3 servers varies widely, and too many are quite poor. If your
28mailserver supports IMAP, you would be better off using the
29:class:`imaplib.IMAP4` class, as IMAP servers tend to be better implemented.
30
31.. include:: ../includes/wasm-notavail.rst
32
33The :mod:`poplib` module provides two classes:
34
35
36.. class:: POP3(host, port=POP3_PORT[, timeout])
37
38   This class implements the actual POP3 protocol.  The connection is created when
39   the instance is initialized. If *port* is omitted, the standard POP3 port (110)
40   is used. The optional *timeout* parameter specifies a timeout in seconds for the
41   connection attempt (if not specified, the global default timeout setting will
42   be used).
43
44   .. audit-event:: poplib.connect self,host,port poplib.POP3
45
46   .. audit-event:: poplib.putline self,line poplib.POP3
47
48      All commands will raise an :ref:`auditing event <auditing>`
49      ``poplib.putline`` with arguments ``self`` and ``line``,
50      where ``line`` is the bytes about to be sent to the remote host.
51
52   .. versionchanged:: 3.9
53      If the *timeout* parameter is set to be zero, it will raise a
54      :class:`ValueError` to prevent the creation of a non-blocking socket.
55
56.. class:: POP3_SSL(host, port=POP3_SSL_PORT, keyfile=None, certfile=None, timeout=None, context=None)
57
58   This is a subclass of :class:`POP3` that connects to the server over an SSL
59   encrypted socket.  If *port* is not specified, 995, the standard POP3-over-SSL
60   port is used.  *timeout* works as in the :class:`POP3` constructor.
61   *context* is an optional :class:`ssl.SSLContext` object which allows
62   bundling SSL configuration options, certificates and private keys into a
63   single (potentially long-lived) structure.  Please read :ref:`ssl-security`
64   for best practices.
65
66   *keyfile* and *certfile* are a legacy alternative to *context* - they can
67   point to PEM-formatted private key and certificate chain files,
68   respectively, for the SSL connection.
69
70   .. audit-event:: poplib.connect self,host,port poplib.POP3_SSL
71
72   .. audit-event:: poplib.putline self,line poplib.POP3_SSL
73
74      All commands will raise an :ref:`auditing event <auditing>`
75      ``poplib.putline`` with arguments ``self`` and ``line``,
76      where ``line`` is the bytes about to be sent to the remote host.
77
78   .. versionchanged:: 3.2
79      *context* parameter added.
80
81   .. versionchanged:: 3.4
82      The class now supports hostname check with
83      :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
84      :data:`ssl.HAS_SNI`).
85
86   .. deprecated:: 3.6
87
88       *keyfile* and *certfile* are deprecated in favor of *context*.
89       Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
90       :func:`ssl.create_default_context` select the system's trusted CA
91       certificates for you.
92
93   .. versionchanged:: 3.9
94      If the *timeout* parameter is set to be zero, it will raise a
95      :class:`ValueError` to prevent the creation of a non-blocking socket.
96
97One exception is defined as an attribute of the :mod:`poplib` module:
98
99
100.. exception:: error_proto
101
102   Exception raised on any errors from this module (errors from :mod:`socket`
103   module are not caught). The reason for the exception is passed to the
104   constructor as a string.
105
106
107.. seealso::
108
109   Module :mod:`imaplib`
110      The standard Python IMAP module.
111
112   `Frequently Asked Questions About Fetchmail <http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html>`_
113      The FAQ for the :program:`fetchmail` POP/IMAP client collects information on
114      POP3 server variations and RFC noncompliance that may be useful if you need to
115      write an application based on the POP protocol.
116
117
118.. _pop3-objects:
119
120POP3 Objects
121------------
122
123All POP3 commands are represented by methods of the same name, in lowercase;
124most return the response text sent by the server.
125
126A :class:`POP3` instance has the following methods:
127
128
129.. method:: POP3.set_debuglevel(level)
130
131   Set the instance's debugging level.  This controls the amount of debugging
132   output printed.  The default, ``0``, produces no debugging output.  A value of
133   ``1`` produces a moderate amount of debugging output, generally a single line
134   per request.  A value of ``2`` or higher produces the maximum amount of
135   debugging output, logging each line sent and received on the control connection.
136
137
138.. method:: POP3.getwelcome()
139
140   Returns the greeting string sent by the POP3 server.
141
142
143.. method:: POP3.capa()
144
145   Query the server's capabilities as specified in :rfc:`2449`.
146   Returns a dictionary in the form ``{'name': ['param'...]}``.
147
148   .. versionadded:: 3.4
149
150
151.. method:: POP3.user(username)
152
153   Send user command, response should indicate that a password is required.
154
155
156.. method:: POP3.pass_(password)
157
158   Send password, response includes message count and mailbox size. Note: the
159   mailbox on the server is locked until :meth:`~poplib.quit` is called.
160
161
162.. method:: POP3.apop(user, secret)
163
164   Use the more secure APOP authentication to log into the POP3 server.
165
166
167.. method:: POP3.rpop(user)
168
169   Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server.
170
171
172.. method:: POP3.stat()
173
174   Get mailbox status.  The result is a tuple of 2 integers: ``(message count,
175   mailbox size)``.
176
177
178.. method:: POP3.list([which])
179
180   Request message list, result is in the form ``(response, ['mesg_num octets',
181   ...], octets)``. If *which* is set, it is the message to list.
182
183
184.. method:: POP3.retr(which)
185
186   Retrieve whole message number *which*, and set its seen flag. Result is in form
187   ``(response, ['line', ...], octets)``.
188
189
190.. method:: POP3.dele(which)
191
192   Flag message number *which* for deletion.  On most servers deletions are not
193   actually performed until QUIT (the major exception is Eudora QPOP, which
194   deliberately violates the RFCs by doing pending deletes on any disconnect).
195
196
197.. method:: POP3.rset()
198
199   Remove any deletion marks for the mailbox.
200
201
202.. method:: POP3.noop()
203
204   Do nothing.  Might be used as a keep-alive.
205
206
207.. method:: POP3.quit()
208
209   Signoff:  commit changes, unlock mailbox, drop connection.
210
211
212.. method:: POP3.top(which, howmuch)
213
214   Retrieves the message header plus *howmuch* lines of the message after the
215   header of message number *which*. Result is in form ``(response, ['line', ...],
216   octets)``.
217
218   The POP3 TOP command this method uses, unlike the RETR command, doesn't set the
219   message's seen flag; unfortunately, TOP is poorly specified in the RFCs and is
220   frequently broken in off-brand servers. Test this method by hand against the
221   POP3 servers you will use before trusting it.
222
223
224.. method:: POP3.uidl(which=None)
225
226   Return message digest (unique id) list. If *which* is specified, result contains
227   the unique id for that message in the form ``'response mesgnum uid``, otherwise
228   result is list ``(response, ['mesgnum uid', ...], octets)``.
229
230
231.. method:: POP3.utf8()
232
233   Try to switch to UTF-8 mode. Returns the server response if successful,
234   raises :class:`error_proto` if not. Specified in :RFC:`6856`.
235
236   .. versionadded:: 3.5
237
238
239.. method:: POP3.stls(context=None)
240
241   Start a TLS session on the active connection as specified in :rfc:`2595`.
242   This is only allowed before user authentication
243
244   *context* parameter is a :class:`ssl.SSLContext` object which allows
245   bundling SSL configuration options, certificates and private keys into
246   a single (potentially long-lived) structure.  Please read :ref:`ssl-security`
247   for best practices.
248
249   This method supports hostname checking via
250   :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
251   :data:`ssl.HAS_SNI`).
252
253   .. versionadded:: 3.4
254
255
256Instances of :class:`POP3_SSL` have no additional methods. The interface of this
257subclass is identical to its parent.
258
259
260.. _pop3-example:
261
262POP3 Example
263------------
264
265Here is a minimal example (without error checking) that opens a mailbox and
266retrieves and prints all messages::
267
268   import getpass, poplib
269
270   M = poplib.POP3('localhost')
271   M.user(getpass.getuser())
272   M.pass_(getpass.getpass())
273   numMessages = len(M.list()[1])
274   for i in range(numMessages):
275       for j in M.retr(i+1)[1]:
276           print(j)
277
278At the end of the module, there is a test section that contains a more extensive
279example of usage.
280