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