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:`2060`. 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 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
117 The 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
127 The 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
159 Note that IMAP4 message numbers change as the mailbox changes; in particular,
160 after an ``EXPUNGE`` command performs deletions the remaining messages are
161 renumbered. So it is highly advisable to use UIDs instead, with the UID command.
162
163 At the end of the module, there is a test section that contains a more extensive
164 example 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
176 IMAP4 Objects
177 -------------
178
179 All IMAP4rev1 commands are represented by methods of the same name, either
180 uppercase or lowercase.
181
182 All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
183 and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If
184 necessary (the string contains IMAP4 protocol-sensitive characters and isn't
185 enclosed with either parentheses or double quotes) each string is quoted.
186 However, the *password* argument to the ``LOGIN`` command is always quoted. If
187 you 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
190 Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
191 ``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
192 or mandated results from the command. Each *data* is either a ``bytes``, or a
193 tuple. If a tuple, then the first part is the header of the response, and the
194 second part contains the data (ie: 'literal' value).
195
196 The *message_set* options to commands below is a string specifying one or more
197 messages to be acted upon. It may be a simple message number (``'1'``), a range
198 of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
199 commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite
200 upper bound (``'3:*'``).
201
202 An :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 .. versionchanged:: 3.13.8
329 An :exc:`IMAP4.error` is raised if MD5 support is not available.
330
331
332 .. method:: IMAP4.logout()
333
334 Shutdown connection to server. Returns server ``BYE`` response.
335
336 .. versionchanged:: 3.8
337 The method no longer ignores silently arbitrary exceptions.
338
339
340 .. method:: IMAP4.lsub(directory='""', pattern='*')
341
342 List subscribed mailbox names in directory matching pattern. *directory*
343 defaults to the top level directory and *pattern* defaults to match any mailbox.
344 Returned data are tuples of message part envelope and data.
345
346
347 .. method:: IMAP4.myrights(mailbox)
348
349 Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
350
351
352 .. method:: IMAP4.namespace()
353
354 Returns IMAP namespaces as defined in :rfc:`2342`.
355
356
357 .. method:: IMAP4.noop()
358
359 Send ``NOOP`` to server.
360
361
362 .. method:: IMAP4.open(host, port, timeout=None)
363
364 Opens socket to *port* at *host*. The optional *timeout* parameter
365 specifies a timeout in seconds for the connection attempt.
366 If timeout is not given or is ``None``, the global default socket timeout
367 is used. Also note that if the *timeout* parameter is set to be zero,
368 it will raise a :class:`ValueError` to reject creating a non-blocking socket.
369 This method is implicitly called by the :class:`IMAP4` constructor.
370 The connection objects established by this method will be used in
371 the :meth:`IMAP4.read`, :meth:`IMAP4.readline`, :meth:`IMAP4.send`,
372 and :meth:`IMAP4.shutdown` methods. You may override this method.
373
374 .. audit-event:: imaplib.open self,host,port imaplib.IMAP4.open
375
376 .. versionchanged:: 3.9
377 The *timeout* parameter was added.
378
379 .. method:: IMAP4.partial(message_num, message_part, start, length)
380
381 Fetch truncated part of a message. Returned data is a tuple of message part
382 envelope and data.
383
384
385 .. method:: IMAP4.proxyauth(user)
386
387 Assume authentication as *user*. Allows an authorised administrator to proxy
388 into any user's mailbox.
389
390
391 .. method:: IMAP4.read(size)
392
393 Reads *size* bytes from the remote server. You may override this method.
394
395
396 .. method:: IMAP4.readline()
397
398 Reads one line from the remote server. You may override this method.
399
400
401 .. method:: IMAP4.recent()
402
403 Prompt server for an update. Returned data is ``None`` if no new messages, else
404 value of ``RECENT`` response.
405
406
407 .. method:: IMAP4.rename(oldmailbox, newmailbox)
408
409 Rename mailbox named *oldmailbox* to *newmailbox*.
410
411
412 .. method:: IMAP4.response(code)
413
414 Return data for response *code* if received, or ``None``. Returns the given
415 code, instead of the usual type.
416
417
418 .. method:: IMAP4.search(charset, criterion[, ...])
419
420 Search mailbox for matching messages. *charset* may be ``None``, in which case
421 no ``CHARSET`` will be specified in the request to the server. The IMAP
422 protocol requires that at least one criterion be specified; an exception will be
423 raised when the server returns an error. *charset* must be ``None`` if
424 the ``UTF8=ACCEPT`` capability was enabled using the :meth:`enable`
425 command.
426
427 Example::
428
429 # M is a connected IMAP4 instance...
430 typ, msgnums = M.search(None, 'FROM', '"LDJ"')
431
432 # or:
433 typ, msgnums = M.search(None, '(FROM "LDJ")')
434
435
436 .. method:: IMAP4.select(mailbox='INBOX', readonly=False)
437
438 Select a mailbox. Returned data is the count of messages in *mailbox*
439 (``EXISTS`` response). The default *mailbox* is ``'INBOX'``. If the *readonly*
440 flag is set, modifications to the mailbox are not allowed.
441
442
443 .. method:: IMAP4.send(data)
444
445 Sends ``data`` to the remote server. You may override this method.
446
447 .. audit-event:: imaplib.send self,data imaplib.IMAP4.send
448
449
450 .. method:: IMAP4.setacl(mailbox, who, what)
451
452 Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
453 the ``Cyrus`` server.
454
455
456 .. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])
457
458 Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
459 supported by the ``Cyrus`` server.
460
461
462 .. method:: IMAP4.setquota(root, limits)
463
464 Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
465 QUOTA extension defined in rfc2087.
466
467
468 .. method:: IMAP4.shutdown()
469
470 Close connection established in ``open``. This method is implicitly
471 called by :meth:`IMAP4.logout`. You may override this method.
472
473
474 .. method:: IMAP4.socket()
475
476 Returns socket instance used to connect to server.
477
478
479 .. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])
480
481 The ``sort`` command is a variant of ``search`` with sorting semantics for the
482 results. Returned data contains a space separated list of matching message
483 numbers.
484
485 Sort has two arguments before the *search_criterion* argument(s); a
486 parenthesized list of *sort_criteria*, and the searching *charset*. Note that
487 unlike ``search``, the searching *charset* argument is mandatory. There is also
488 a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
489 corresponds to ``search``. The ``sort`` command first searches the mailbox for
490 messages that match the given searching criteria using the charset argument for
491 the interpretation of strings in the searching criteria. It then returns the
492 numbers of matching messages.
493
494 This is an ``IMAP4rev1`` extension command.
495
496
497 .. method:: IMAP4.starttls(ssl_context=None)
498
499 Send a ``STARTTLS`` command. The *ssl_context* argument is optional
500 and should be a :class:`ssl.SSLContext` object. This will enable
501 encryption on the IMAP connection. Please read :ref:`ssl-security` for
502 best practices.
503
504 .. versionadded:: 3.2
505
506 .. versionchanged:: 3.4
507 The method now supports hostname check with
508 :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
509 :const:`ssl.HAS_SNI`).
510
511
512 .. method:: IMAP4.status(mailbox, names)
513
514 Request named status conditions for *mailbox*.
515
516
517 .. method:: IMAP4.store(message_set, command, flag_list)
518
519 Alters flag dispositions for messages in mailbox. *command* is specified by
520 section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
521 optionally with a suffix of ".SILENT".
522
523 For example, to set the delete flag on all messages::
524
525 typ, data = M.search(None, 'ALL')
526 for num in data[0].split():
527 M.store(num, '+FLAGS', '\\Deleted')
528 M.expunge()
529
530 .. note::
531
532 Creating flags containing ']' (for example: "[test]") violates
533 :rfc:`3501` (the IMAP protocol). However, imaplib has historically
534 allowed creation of such tags, and popular IMAP servers, such as Gmail,
535 accept and produce such flags. There are non-Python programs which also
536 create such tags. Although it is an RFC violation and IMAP clients and
537 servers are supposed to be strict, imaplib still continues to allow
538 such tags to be created for backward compatibility reasons, and as of
539 Python 3.6, handles them if they are sent from the server, since this
540 improves real-world compatibility.
541
542 .. method:: IMAP4.subscribe(mailbox)
543
544 Subscribe to new mailbox.
545
546
547 .. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])
548
549 The ``thread`` command is a variant of ``search`` with threading semantics for
550 the results. Returned data contains a space separated list of thread members.
551
552 Thread members consist of zero or more messages numbers, delimited by spaces,
553 indicating successive parent and child.
554
555 Thread has two arguments before the *search_criterion* argument(s); a
556 *threading_algorithm*, and the searching *charset*. Note that unlike
557 ``search``, the searching *charset* argument is mandatory. There is also a
558 ``uid thread`` command which corresponds to ``thread`` the way that ``uid
559 search`` corresponds to ``search``. The ``thread`` command first searches the
560 mailbox for messages that match the given searching criteria using the *charset*
561 argument for the interpretation of strings in the searching criteria. It then
562 returns the matching messages threaded according to the specified threading
563 algorithm.
564
565 This is an ``IMAP4rev1`` extension command.
566
567
568 .. method:: IMAP4.uid(command, arg[, ...])
569
570 Execute command args with messages identified by UID, rather than message
571 number. Returns response appropriate to command. At least one argument must be
572 supplied; if none are provided, the server will return an error and an exception
573 will be raised.
574
575
576 .. method:: IMAP4.unsubscribe(mailbox)
577
578 Unsubscribe from old mailbox.
579
580 .. method:: IMAP4.unselect()
581
582 :meth:`imaplib.IMAP4.unselect` frees server's resources associated with the
583 selected mailbox and returns the server to the authenticated
584 state. This command performs the same actions as :meth:`imaplib.IMAP4.close`, except
585 that no messages are permanently removed from the currently
586 selected mailbox.
587
588 .. versionadded:: 3.9
589
590 .. method:: IMAP4.xatom(name[, ...])
591
592 Allow simple extension commands notified by server in ``CAPABILITY`` response.
593
594
595 The following attributes are defined on instances of :class:`IMAP4`:
596
597 .. attribute:: IMAP4.PROTOCOL_VERSION
598
599 The most recent supported protocol in the ``CAPABILITY`` response from the
600 server.
601
602
603 .. attribute:: IMAP4.debug
604
605 Integer value to control debugging output. The initialize value is taken from
606 the module variable ``Debug``. Values greater than three trace each command.
607
608
609 .. attribute:: IMAP4.utf8_enabled
610
611 Boolean value that is normally ``False``, but is set to ``True`` if an
612 :meth:`enable` command is successfully issued for the ``UTF8=ACCEPT``
613 capability.
614
615 .. versionadded:: 3.5
616
617
618 .. _imap4-example:
619
620 IMAP4 Example
621 -------------
622
623 Here is a minimal example (without error checking) that opens a mailbox and
624 retrieves and prints all messages::
625
626 import getpass, imaplib
627
628 M = imaplib.IMAP4(host='example.org')
629 M.login(getpass.getuser(), getpass.getpass())
630 M.select()
631 typ, data = M.search(None, 'ALL')
632 for num in data[0].split():
633 typ, data = M.fetch(num, '(RFC822)')
634 print('Message %s\n%s\n' % (num, data[0][1]))
635 M.close()
636 M.logout()
637