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