Debian Codegraph @

Doc/library/imaplib.rst

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