1:mod:`imaplib` --- IMAP4 protocol client
2========================================
3
4.. module:: imaplib
5   :synopsis: IMAP4 protocol client (requires sockets).
6
7.. moduleauthor:: Piers Lauder <[email protected]>
8.. sectionauthor:: Piers Lauder <[email protected]>
9.. revised by ESR, January 2000
10.. changes for IMAP4_SSL by Tino Lange <[email protected]>, March 2002
11.. changes for IMAP4_stream by Piers Lauder <[email protected]>,
12   November 2002
13
14**Source code:** :source:`Lib/imaplib.py`
15
16.. index::
17   pair: IMAP4; protocol
18   pair: IMAP4_SSL; protocol
19   pair: IMAP4_stream; protocol
20
21--------------
22
23This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and
24:class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and
25implement a large subset of the IMAP4rev1 client protocol as defined in
26:rfc:`2060`. It is backward compatible with IMAP4 (:rfc:`1730`) servers, but
27note that the ``STATUS`` command is not supported in IMAP4.
28
29.. include:: ../includes/wasm-notavail.rst
30
31Three classes are provided by the :mod:`imaplib` module, :class:`IMAP4` is the
32base class:
33
34
35.. class:: IMAP4(host='', port=IMAP4_PORT, timeout=None)
36
37   This class implements the actual IMAP4 protocol.  The connection is created and
38   protocol version (IMAP4 or IMAP4rev1) is determined when the instance is
39   initialized. If *host* is not specified, ``''`` (the local host) is used. If
40   *port* is omitted, the standard IMAP4 port (143) is used. The optional *timeout*
41   parameter specifies a timeout in seconds for the connection attempt.
42   If timeout is not given or is None, the global default socket timeout is used.
43
44   The :class:`IMAP4` class supports the :keyword:`with` statement.  When used
45   like this, the IMAP4 ``LOGOUT`` command is issued automatically when the
46   :keyword:`!with` statement exits.  E.g.::
47
48    >>> from imaplib import IMAP4
49    >>> with IMAP4("domain.org") as M:
50    ...     M.noop()
51    ...
52    ('OK', [b'Nothing Accomplished. d25if65hy903weo.87'])
53
54   .. versionchanged:: 3.5
55      Support for the :keyword:`with` statement was added.
56
57   .. versionchanged:: 3.9
58      The optional *timeout* parameter was added.
59
60Three exceptions are defined as attributes of the :class:`IMAP4` class:
61
62
63.. exception:: IMAP4.error
64
65   Exception raised on any errors.  The reason for the exception is passed to the
66   constructor as a string.
67
68
69.. exception:: IMAP4.abort
70
71   IMAP4 server errors cause this exception to be raised.  This is a sub-class of
72   :exc:`IMAP4.error`.  Note that closing the instance and instantiating a new one
73   will usually allow recovery from this exception.
74
75
76.. exception:: IMAP4.readonly
77
78   This exception is raised when a writable mailbox has its status changed by the
79   server.  This is a sub-class of :exc:`IMAP4.error`.  Some other client now has
80   write permission, and the mailbox will need to be re-opened to re-obtain write
81   permission.
82
83
84There's also a subclass for secure connections:
85
86
87.. class:: IMAP4_SSL(host='', port=IMAP4_SSL_PORT, keyfile=None, \
88                     certfile=None, ssl_context=None, timeout=None)
89
90   This is a subclass derived from :class:`IMAP4` that connects over an SSL
91   encrypted socket (to use this class you need a socket module that was compiled
92   with SSL support).  If *host* is not specified, ``''`` (the local host) is used.
93   If *port* is omitted, the standard IMAP4-over-SSL port (993) is used.
94   *ssl_context* is a :class:`ssl.SSLContext` object which allows bundling
95   SSL configuration options, certificates and private keys into a single
96   (potentially long-lived) structure.  Please read :ref:`ssl-security` for
97   best practices.
98
99   *keyfile* and *certfile* are a legacy alternative to *ssl_context* - they
100   can point to PEM-formatted private key and certificate chain files for
101   the SSL connection.  Note that the *keyfile*/*certfile* parameters are
102   mutually exclusive with *ssl_context*, a :class:`ValueError` is raised
103   if *keyfile*/*certfile* is provided along with *ssl_context*.
104
105   The optional *timeout* parameter specifies a timeout in seconds for the
106   connection attempt. If timeout is not given or is None, the global default
107   socket timeout is used.
108
109   .. versionchanged:: 3.3
110      *ssl_context* parameter was added.
111
112   .. versionchanged:: 3.4
113      The class now supports hostname check with
114      :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
115      :data:`ssl.HAS_SNI`).
116
117   .. deprecated:: 3.6
118
119       *keyfile* and *certfile* are deprecated in favor of *ssl_context*.
120       Please use :meth:`ssl.SSLContext.load_cert_chain` instead, or let
121       :func:`ssl.create_default_context` select the system's trusted CA
122       certificates for you.
123
124   .. versionchanged:: 3.9
125      The optional *timeout* parameter was added.
126
127The second subclass allows for connections created by a child process:
128
129
130.. class:: IMAP4_stream(command)
131
132   This is a subclass derived from :class:`IMAP4` that connects to the
133   ``stdin/stdout`` file descriptors created by passing *command* to
134   ``subprocess.Popen()``.
135
136
137The following utility functions are defined:
138
139
140.. function:: Internaldate2tuple(datestr)
141
142   Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
143   time.  The return value is a :class:`time.struct_time` tuple or
144   ``None`` if the string has wrong format.
145
146.. function:: Int2AP(num)
147
148   Converts an integer into a bytes representation using characters from the set
149   [``A`` .. ``P``].
150
151
152.. function:: ParseFlags(flagstr)
153
154   Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags.
155
156
157.. function:: Time2Internaldate(date_time)
158
159   Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation.
160   The return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS
161   +HHMM"`` (including double-quotes).  The *date_time* argument can
162   be a number (int or float) representing seconds since epoch (as
163   returned by :func:`time.time`), a 9-tuple representing local time
164   an instance of :class:`time.struct_time` (as returned by
165   :func:`time.localtime`), an aware instance of
166   :class:`datetime.datetime`, or a double-quoted string.  In the last
167   case, it is assumed to already be in the correct format.
168
169Note that IMAP4 message numbers change as the mailbox changes; in particular,
170after an ``EXPUNGE`` command performs deletions the remaining messages are
171renumbered. So it is highly advisable to use UIDs instead, with the UID command.
172
173At the end of the module, there is a test section that contains a more extensive
174example of usage.
175
176
177.. seealso::
178
179   Documents describing the protocol, sources for servers
180   implementing it, by the University of Washington's IMAP Information Center
181   can all be found at (**Source Code**) https://github.com/uw-imap/imap (**Not Maintained**).
182
183
184.. _imap4-objects:
185
186IMAP4 Objects
187-------------
188
189All IMAP4rev1 commands are represented by methods of the same name, either
190upper-case or lower-case.
191
192All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
193and the last argument to ``APPEND`` which is passed as an IMAP4 literal.  If
194necessary (the string contains IMAP4 protocol-sensitive characters and isn't
195enclosed with either parentheses or double quotes) each string is quoted.
196However, the *password* argument to the ``LOGIN`` command is always quoted. If
197you want to avoid having an argument string quoted (eg: the *flags* argument to
198``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``).
199
200Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
201``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
202or mandated results from the command. Each *data* is either a ``bytes``, or a
203tuple. If a tuple, then the first part is the header of the response, and the
204second part contains the data (ie: 'literal' value).
205
206The *message_set* options to commands below is a string specifying one or more
207messages to be acted upon.  It may be a simple message number (``'1'``), a range
208of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
209commas (``'1:3,6:9'``).  A range can contain an asterisk to indicate an infinite
210upper bound (``'3:*'``).
211
212An :class:`IMAP4` instance has the following methods:
213
214
215.. method:: IMAP4.append(mailbox, flags, date_time, message)
216
217   Append *message* to named mailbox.
218
219
220.. method:: IMAP4.authenticate(mechanism, authobject)
221
222   Authenticate command --- requires response processing.
223
224   *mechanism* specifies which authentication mechanism is to be used - it should
225   appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``.
226
227   *authobject* must be a callable object::
228
229      data = authobject(response)
230
231   It will be called to process server continuation responses; the *response*
232   argument it is passed will be ``bytes``.  It should return ``bytes`` *data*
233   that will be base64 encoded and sent to the server.  It should return
234   ``None`` if the client abort response ``*`` should be sent instead.
235
236   .. versionchanged:: 3.5
237      string usernames and passwords are now encoded to ``utf-8`` instead of
238      being limited to ASCII.
239
240
241.. method:: IMAP4.check()
242
243   Checkpoint mailbox on server.
244
245
246.. method:: IMAP4.close()
247
248   Close currently selected mailbox. Deleted messages are removed from writable
249   mailbox. This is the recommended command before ``LOGOUT``.
250
251
252.. method:: IMAP4.copy(message_set, new_mailbox)
253
254   Copy *message_set* messages onto end of *new_mailbox*.
255
256
257.. method:: IMAP4.create(mailbox)
258
259   Create new mailbox named *mailbox*.
260
261
262.. method:: IMAP4.delete(mailbox)
263
264   Delete old mailbox named *mailbox*.
265
266
267.. method:: IMAP4.deleteacl(mailbox, who)
268
269   Delete the ACLs (remove any rights) set for who on mailbox.
270
271
272.. method:: IMAP4.enable(capability)
273
274   Enable *capability* (see :rfc:`5161`).  Most capabilities do not need to be
275   enabled.  Currently only the ``UTF8=ACCEPT`` capability is supported
276   (see :RFC:`6855`).
277
278   .. versionadded:: 3.5
279      The :meth:`enable` method itself, and :RFC:`6855` support.
280
281
282.. method:: IMAP4.expunge()
283
284   Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
285   response for each deleted message. Returned data contains a list of ``EXPUNGE``
286   message numbers in order received.
287
288
289.. method:: IMAP4.fetch(message_set, message_parts)
290
291   Fetch (parts of) messages.  *message_parts* should be a string of message part
292   names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``.  Returned data
293   are tuples of message part envelope and data.
294
295
296.. method:: IMAP4.getacl(mailbox)
297
298   Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
299   by the ``Cyrus`` server.
300
301
302.. method:: IMAP4.getannotation(mailbox, entry, attribute)
303
304   Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
305   non-standard, but is supported by the ``Cyrus`` server.
306
307
308.. method:: IMAP4.getquota(root)
309
310   Get the ``quota`` *root*'s resource usage and limits. This method is part of the
311   IMAP4 QUOTA extension defined in rfc2087.
312
313
314.. method:: IMAP4.getquotaroot(mailbox)
315
316   Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
317   of the IMAP4 QUOTA extension defined in rfc2087.
318
319
320.. method:: IMAP4.list([directory[, pattern]])
321
322   List mailbox names in *directory* matching *pattern*.  *directory* defaults to
323   the top-level mail folder, and *pattern* defaults to match anything.  Returned
324   data contains a list of ``LIST`` responses.
325
326
327.. method:: IMAP4.login(user, password)
328
329   Identify the client using a plaintext password. The *password* will be quoted.
330
331
332.. method:: IMAP4.login_cram_md5(user, password)
333
334   Force use of ``CRAM-MD5`` authentication when identifying the client to protect
335   the password.  Will only work if the server ``CAPABILITY`` response includes the
336   phrase ``AUTH=CRAM-MD5``.
337
338
339.. method:: IMAP4.logout()
340
341   Shutdown connection to server. Returns server ``BYE`` response.
342
343   .. versionchanged:: 3.8
344      The method no longer ignores silently arbitrary exceptions.
345
346
347.. method:: IMAP4.lsub(directory='""', pattern='*')
348
349   List subscribed mailbox names in directory matching pattern. *directory*
350   defaults to the top level directory and *pattern* defaults to match any mailbox.
351   Returned data are tuples of message part envelope and data.
352
353
354.. method:: IMAP4.myrights(mailbox)
355
356   Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
357
358
359.. method:: IMAP4.namespace()
360
361   Returns IMAP namespaces as defined in :rfc:`2342`.
362
363
364.. method:: IMAP4.noop()
365
366   Send ``NOOP`` to server.
367
368
369.. method:: IMAP4.open(host, port, timeout=None)
370
371   Opens socket to *port* at *host*. The optional *timeout* parameter
372   specifies a timeout in seconds for the connection attempt.
373   If timeout is not given or is None, the global default socket timeout
374   is used. Also note that if the *timeout* parameter is set to be zero,
375   it will raise a :class:`ValueError` to reject creating a non-blocking socket.
376   This method is implicitly called by the :class:`IMAP4` constructor.
377   The connection objects established by this method will be used in
378   the :meth:`IMAP4.read`, :meth:`IMAP4.readline`, :meth:`IMAP4.send`,
379   and :meth:`IMAP4.shutdown` methods. You may override this method.
380
381   .. audit-event:: imaplib.open self,host,port imaplib.IMAP4.open
382
383   .. versionchanged:: 3.9
384      The *timeout* parameter was added.
385
386.. method:: IMAP4.partial(message_num, message_part, start, length)
387
388   Fetch truncated part of a message. Returned data is a tuple of message part
389   envelope and data.
390
391
392.. method:: IMAP4.proxyauth(user)
393
394   Assume authentication as *user*. Allows an authorised administrator to proxy
395   into any user's mailbox.
396
397
398.. method:: IMAP4.read(size)
399
400   Reads *size* bytes from the remote server. You may override this method.
401
402
403.. method:: IMAP4.readline()
404
405   Reads one line from the remote server. You may override this method.
406
407
408.. method:: IMAP4.recent()
409
410   Prompt server for an update. Returned data is ``None`` if no new messages, else
411   value of ``RECENT`` response.
412
413
414.. method:: IMAP4.rename(oldmailbox, newmailbox)
415
416   Rename mailbox named *oldmailbox* to *newmailbox*.
417
418
419.. method:: IMAP4.response(code)
420
421   Return data for response *code* if received, or ``None``. Returns the given
422   code, instead of the usual type.
423
424
425.. method:: IMAP4.search(charset, criterion[, ...])
426
427   Search mailbox for matching messages.  *charset* may be ``None``, in which case
428   no ``CHARSET`` will be specified in the request to the server.  The IMAP
429   protocol requires that at least one criterion be specified; an exception will be
430   raised when the server returns an error.  *charset* must be ``None`` if
431   the ``UTF8=ACCEPT`` capability was enabled using the :meth:`enable`
432   command.
433
434   Example::
435
436      # M is a connected IMAP4 instance...
437      typ, msgnums = M.search(None, 'FROM', '"LDJ"')
438
439      # or:
440      typ, msgnums = M.search(None, '(FROM "LDJ")')
441
442
443.. method:: IMAP4.select(mailbox='INBOX', readonly=False)
444
445   Select a mailbox. Returned data is the count of messages in *mailbox*
446   (``EXISTS`` response).  The default *mailbox* is ``'INBOX'``.  If the *readonly*
447   flag is set, modifications to the mailbox are not allowed.
448
449
450.. method:: IMAP4.send(data)
451
452   Sends ``data`` to the remote server. You may override this method.
453
454   .. audit-event:: imaplib.send self,data imaplib.IMAP4.send
455
456
457.. method:: IMAP4.setacl(mailbox, who, what)
458
459   Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
460   the ``Cyrus`` server.
461
462
463.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])
464
465   Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
466   supported by the ``Cyrus`` server.
467
468
469.. method:: IMAP4.setquota(root, limits)
470
471   Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
472   QUOTA extension defined in rfc2087.
473
474
475.. method:: IMAP4.shutdown()
476
477   Close connection established in ``open``.  This method is implicitly
478   called by :meth:`IMAP4.logout`.  You may override this method.
479
480
481.. method:: IMAP4.socket()
482
483   Returns socket instance used to connect to server.
484
485
486.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])
487
488   The ``sort`` command is a variant of ``search`` with sorting semantics for the
489   results.  Returned data contains a space separated list of matching message
490   numbers.
491
492   Sort has two arguments before the *search_criterion* argument(s); a
493   parenthesized list of *sort_criteria*, and the searching *charset*.  Note that
494   unlike ``search``, the searching *charset* argument is mandatory.  There is also
495   a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
496   corresponds to ``search``.  The ``sort`` command first searches the mailbox for
497   messages that match the given searching criteria using the charset argument for
498   the interpretation of strings in the searching criteria.  It then returns the
499   numbers of matching messages.
500
501   This is an ``IMAP4rev1`` extension command.
502
503
504.. method:: IMAP4.starttls(ssl_context=None)
505
506   Send a ``STARTTLS`` command.  The *ssl_context* argument is optional
507   and should be a :class:`ssl.SSLContext` object.  This will enable
508   encryption on the IMAP connection.  Please read :ref:`ssl-security` for
509   best practices.
510
511   .. versionadded:: 3.2
512
513   .. versionchanged:: 3.4
514      The method now supports hostname check with
515      :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
516      :data:`ssl.HAS_SNI`).
517
518
519.. method:: IMAP4.status(mailbox, names)
520
521   Request named status conditions for *mailbox*.
522
523
524.. method:: IMAP4.store(message_set, command, flag_list)
525
526   Alters flag dispositions for messages in mailbox.  *command* is specified by
527   section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
528   optionally with a suffix of ".SILENT".
529
530   For example, to set the delete flag on all messages::
531
532      typ, data = M.search(None, 'ALL')
533      for num in data[0].split():
534         M.store(num, '+FLAGS', '\\Deleted')
535      M.expunge()
536
537   .. note::
538
539      Creating flags containing ']' (for example: "[test]") violates
540      :rfc:`3501` (the IMAP protocol).  However, imaplib has historically
541      allowed creation of such tags, and popular IMAP servers, such as Gmail,
542      accept and produce such flags.  There are non-Python programs which also
543      create such tags.  Although it is an RFC violation and IMAP clients and
544      servers are supposed to be strict, imaplib nonetheless continues to allow
545      such tags to be created for backward compatibility reasons, and as of
546      Python 3.6, handles them if they are sent from the server, since this
547      improves real-world compatibility.
548
549.. method:: IMAP4.subscribe(mailbox)
550
551   Subscribe to new mailbox.
552
553
554.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])
555
556   The ``thread`` command is a variant of ``search`` with threading semantics for
557   the results.  Returned data contains a space separated list of thread members.
558
559   Thread members consist of zero or more messages numbers, delimited by spaces,
560   indicating successive parent and child.
561
562   Thread has two arguments before the *search_criterion* argument(s); a
563   *threading_algorithm*, and the searching *charset*.  Note that unlike
564   ``search``, the searching *charset* argument is mandatory.  There is also a
565   ``uid thread`` command which corresponds to ``thread`` the way that ``uid
566   search`` corresponds to ``search``.  The ``thread`` command first searches the
567   mailbox for messages that match the given searching criteria using the charset
568   argument for the interpretation of strings in the searching criteria. It then
569   returns the matching messages threaded according to the specified threading
570   algorithm.
571
572   This is an ``IMAP4rev1`` extension command.
573
574
575.. method:: IMAP4.uid(command, arg[, ...])
576
577   Execute command args with messages identified by UID, rather than message
578   number.  Returns response appropriate to command.  At least one argument must be
579   supplied; if none are provided, the server will return an error and an exception
580   will be raised.
581
582
583.. method:: IMAP4.unsubscribe(mailbox)
584
585   Unsubscribe from old mailbox.
586
587.. method:: IMAP4.unselect()
588
589   :meth:`imaplib.IMAP4.unselect` frees server's resources associated with the
590   selected mailbox and returns the server to the authenticated
591   state. This command performs the same actions as :meth:`imaplib.IMAP4.close`, except
592   that no messages are permanently removed from the currently
593   selected mailbox.
594
595   .. versionadded:: 3.9
596
597.. method:: IMAP4.xatom(name[, ...])
598
599   Allow simple extension commands notified by server in ``CAPABILITY`` response.
600
601
602The following attributes are defined on instances of :class:`IMAP4`:
603
604.. attribute:: IMAP4.PROTOCOL_VERSION
605
606   The most recent supported protocol in the ``CAPABILITY`` response from the
607   server.
608
609
610.. attribute:: IMAP4.debug
611
612   Integer value to control debugging output.  The initialize value is taken from
613   the module variable ``Debug``.  Values greater than three trace each command.
614
615
616.. attribute:: IMAP4.utf8_enabled
617
618   Boolean value that is normally ``False``, but is set to ``True`` if an
619   :meth:`enable` command is successfully issued for the ``UTF8=ACCEPT``
620   capability.
621
622   .. versionadded:: 3.5
623
624
625.. _imap4-example:
626
627IMAP4 Example
628-------------
629
630Here is a minimal example (without error checking) that opens a mailbox and
631retrieves and prints all messages::
632
633   import getpass, imaplib
634
635   M = imaplib.IMAP4()
636   M.login(getpass.getuser(), getpass.getpass())
637   M.select()
638   typ, data = M.search(None, 'ALL')
639   for num in data[0].split():
640       typ, data = M.fetch(num, '(RFC822)')
641       print('Message %s\n%s\n' % (num, data[0][1]))
642   M.close()
643   M.logout()
644
645