blob: be2f599b0c4ce3197a18ce401379f07fd2c477a8 [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).
6.. moduleauthor:: Piers Lauder <piers@communitysolutions.com.au>
7.. sectionauthor:: Piers Lauder <piers@communitysolutions.com.au>
Christian Heimes5b5e81c2007-12-31 16:14:33 +00008.. revised by ESR, January 2000
9.. changes for IMAP4_SSL by Tino Lange <Tino.Lange@isg.de>, March 2002
10.. changes for IMAP4_stream by Piers Lauder <piers@communitysolutions.com.au>,
11 November 2002
Georg Brandl116aa622007-08-15 14:28:22 +000012
13
14.. index::
15 pair: IMAP4; protocol
16 pair: IMAP4_SSL; protocol
17 pair: IMAP4_stream; protocol
18
Raymond Hettinger469271d2011-01-27 20:38:46 +000019**Source code:** :source:`Lib/imaplib.py`
20
21--------------
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
40Three exceptions are defined as attributes of the :class:`IMAP4` class:
41
42
43.. exception:: IMAP4.error
44
45 Exception raised on any errors. The reason for the exception is passed to the
46 constructor as a string.
47
48
49.. exception:: IMAP4.abort
50
51 IMAP4 server errors cause this exception to be raised. This is a sub-class of
52 :exc:`IMAP4.error`. Note that closing the instance and instantiating a new one
53 will usually allow recovery from this exception.
54
55
56.. exception:: IMAP4.readonly
57
58 This exception is raised when a writable mailbox has its status changed by the
59 server. This is a sub-class of :exc:`IMAP4.error`. Some other client now has
60 write permission, and the mailbox will need to be re-opened to re-obtain write
61 permission.
62
Antoine Pitrouf3b001f2010-11-12 18:49:16 +000063
Georg Brandl116aa622007-08-15 14:28:22 +000064There's also a subclass for secure connections:
65
66
Antoine Pitrou08728162011-05-06 18:49:52 +020067.. class:: IMAP4_SSL(host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None)
Georg Brandl116aa622007-08-15 14:28:22 +000068
69 This is a subclass derived from :class:`IMAP4` that connects over an SSL
70 encrypted socket (to use this class you need a socket module that was compiled
71 with SSL support). If *host* is not specified, ``''`` (the local host) is used.
72 If *port* is omitted, the standard IMAP4-over-SSL port (993) is used. *keyfile*
73 and *certfile* are also optional - they can contain a PEM formatted private key
Antoine Pitrou08728162011-05-06 18:49:52 +020074 and certificate chain file for the SSL connection. *ssl_context* parameter is a
75 :class:`ssl.SSLContext` object which allows bundling SSL configuration
76 options, certificates and private keys into a single (potentially long-lived)
77 structure. Note that the *keyfile*/*certfile* parameters are mutually exclusive with *ssl_context*,
Andrew Svetlov5b898402012-12-18 21:26:36 +020078 a :class:`ValueError` is raised if *keyfile*/*certfile* is provided along with *ssl_context*.
Antoine Pitrou08728162011-05-06 18:49:52 +020079
80 .. versionchanged:: 3.3
81 *ssl_context* parameter added.
Georg Brandl116aa622007-08-15 14:28:22 +000082
Christian Heimes48aae572013-12-02 20:01:29 +010083 .. versionchanged:: 3.4
84 The class now supports hostname check with
85 :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see
86 :data:`~ssl.HAS_SNI`).
Antoine Pitrouf3b001f2010-11-12 18:49:16 +000087
Georg Brandl116aa622007-08-15 14:28:22 +000088The second subclass allows for connections created by a child process:
89
90
91.. class:: IMAP4_stream(command)
92
93 This is a subclass derived from :class:`IMAP4` that connects to the
94 ``stdin/stdout`` file descriptors created by passing *command* to
Christian Heimesfb5faf02008-11-05 19:39:50 +000095 ``subprocess.Popen()``.
Georg Brandl116aa622007-08-15 14:28:22 +000096
Georg Brandl116aa622007-08-15 14:28:22 +000097
98The following utility functions are defined:
99
100
101.. function:: Internaldate2tuple(datestr)
102
Alexander Belopolsky41a99bc2011-01-19 19:53:30 +0000103 Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
104 time. The return value is a :class:`time.struct_time` tuple or
105 None if the string has wrong format.
Georg Brandl116aa622007-08-15 14:28:22 +0000106
107.. function:: Int2AP(num)
108
109 Converts an integer into a string representation using characters from the set
110 [``A`` .. ``P``].
111
112
113.. function:: ParseFlags(flagstr)
114
115 Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags.
116
117
118.. function:: Time2Internaldate(date_time)
119
Alexander Belopolsky8141cc72012-06-22 21:03:39 -0400120 Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation.
121 The return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS
122 +HHMM"`` (including double-quotes). The *date_time* argument can
123 be a number (int or float) representing seconds since epoch (as
124 returned by :func:`time.time`), a 9-tuple representing local time
125 an instance of :class:`time.struct_time` (as returned by
126 :func:`time.localtime`), an aware instance of
127 :class:`datetime.datetime`, or a double-quoted string. In the last
128 case, it is assumed to already be in the correct format.
Georg Brandl116aa622007-08-15 14:28:22 +0000129
130Note that IMAP4 message numbers change as the mailbox changes; in particular,
131after an ``EXPUNGE`` command performs deletions the remaining messages are
132renumbered. So it is highly advisable to use UIDs instead, with the UID command.
133
134At the end of the module, there is a test section that contains a more extensive
135example of usage.
136
137
138.. seealso::
139
140 Documents describing the protocol, and sources and binaries for servers
141 implementing it, can all be found at the University of Washington's *IMAP
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000142 Information Center* (http://www.washington.edu/imap/).
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144
145.. _imap4-objects:
146
147IMAP4 Objects
148-------------
149
150All IMAP4rev1 commands are represented by methods of the same name, either
151upper-case or lower-case.
152
153All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
154and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If
155necessary (the string contains IMAP4 protocol-sensitive characters and isn't
156enclosed with either parentheses or double quotes) each string is quoted.
157However, the *password* argument to the ``LOGIN`` command is always quoted. If
158you want to avoid having an argument string quoted (eg: the *flags* argument to
159``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``).
160
161Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
162``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
163or mandated results from the command. Each *data* is either a string, or a
164tuple. If a tuple, then the first part is the header of the response, and the
165second part contains the data (ie: 'literal' value).
166
167The *message_set* options to commands below is a string specifying one or more
168messages to be acted upon. It may be a simple message number (``'1'``), a range
169of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
170commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite
171upper bound (``'3:*'``).
172
173An :class:`IMAP4` instance has the following methods:
174
175
176.. method:: IMAP4.append(mailbox, flags, date_time, message)
177
178 Append *message* to named mailbox.
179
180
181.. method:: IMAP4.authenticate(mechanism, authobject)
182
183 Authenticate command --- requires response processing.
184
185 *mechanism* specifies which authentication mechanism is to be used - it should
186 appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``.
187
188 *authobject* must be a callable object::
189
190 data = authobject(response)
191
R David Murray774a39f2013-02-19 12:17:31 -0500192 It will be called to process server continuation responses; the *response*
193 argument it is passed will be ``bytes``. It should return ``bytes`` *data*
194 that will be base64 encoded and sent to the server. It should return
195 ``None`` if the client abort response ``*`` should be sent instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000196
197
198.. method:: IMAP4.check()
199
200 Checkpoint mailbox on server.
201
202
203.. method:: IMAP4.close()
204
205 Close currently selected mailbox. Deleted messages are removed from writable
206 mailbox. This is the recommended command before ``LOGOUT``.
207
208
209.. method:: IMAP4.copy(message_set, new_mailbox)
210
211 Copy *message_set* messages onto end of *new_mailbox*.
212
213
214.. method:: IMAP4.create(mailbox)
215
216 Create new mailbox named *mailbox*.
217
218
219.. method:: IMAP4.delete(mailbox)
220
221 Delete old mailbox named *mailbox*.
222
223
224.. method:: IMAP4.deleteacl(mailbox, who)
225
226 Delete the ACLs (remove any rights) set for who on mailbox.
227
Georg Brandl116aa622007-08-15 14:28:22 +0000228
229.. method:: IMAP4.expunge()
230
231 Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
232 response for each deleted message. Returned data contains a list of ``EXPUNGE``
233 message numbers in order received.
234
235
236.. method:: IMAP4.fetch(message_set, message_parts)
237
238 Fetch (parts of) messages. *message_parts* should be a string of message part
239 names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data
240 are tuples of message part envelope and data.
241
242
243.. method:: IMAP4.getacl(mailbox)
244
245 Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
246 by the ``Cyrus`` server.
247
248
249.. method:: IMAP4.getannotation(mailbox, entry, attribute)
250
251 Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
252 non-standard, but is supported by the ``Cyrus`` server.
253
Georg Brandl116aa622007-08-15 14:28:22 +0000254
255.. method:: IMAP4.getquota(root)
256
257 Get the ``quota`` *root*'s resource usage and limits. This method is part of the
258 IMAP4 QUOTA extension defined in rfc2087.
259
Georg Brandl116aa622007-08-15 14:28:22 +0000260
261.. method:: IMAP4.getquotaroot(mailbox)
262
263 Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
264 of the IMAP4 QUOTA extension defined in rfc2087.
265
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267.. method:: IMAP4.list([directory[, pattern]])
268
269 List mailbox names in *directory* matching *pattern*. *directory* defaults to
270 the top-level mail folder, and *pattern* defaults to match anything. Returned
271 data contains a list of ``LIST`` responses.
272
273
274.. method:: IMAP4.login(user, password)
275
276 Identify the client using a plaintext password. The *password* will be quoted.
277
278
279.. method:: IMAP4.login_cram_md5(user, password)
280
281 Force use of ``CRAM-MD5`` authentication when identifying the client to protect
282 the password. Will only work if the server ``CAPABILITY`` response includes the
283 phrase ``AUTH=CRAM-MD5``.
284
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286.. method:: IMAP4.logout()
287
288 Shutdown connection to server. Returns server ``BYE`` response.
289
290
Georg Brandl3dd33882009-06-01 17:35:27 +0000291.. method:: IMAP4.lsub(directory='""', pattern='*')
Georg Brandl116aa622007-08-15 14:28:22 +0000292
293 List subscribed mailbox names in directory matching pattern. *directory*
294 defaults to the top level directory and *pattern* defaults to match any mailbox.
295 Returned data are tuples of message part envelope and data.
296
297
298.. method:: IMAP4.myrights(mailbox)
299
300 Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
301
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303.. method:: IMAP4.namespace()
304
305 Returns IMAP namespaces as defined in RFC2342.
306
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308.. method:: IMAP4.noop()
309
310 Send ``NOOP`` to server.
311
312
313.. method:: IMAP4.open(host, port)
314
Antoine Pitroufdded562011-02-07 15:58:11 +0000315 Opens socket to *port* at *host*. This method is implicitly called by
316 the :class:`IMAP4` constructor. The connection objects established by this
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300317 method will be used in the :meth:`IMAP4.read`, :meth:`IMAP4.readline`,
318 :meth:`IMAP4.send`, and :meth:`IMAP4.shutdown` methods. You may override
319 this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000320
321
322.. method:: IMAP4.partial(message_num, message_part, start, length)
323
324 Fetch truncated part of a message. Returned data is a tuple of message part
325 envelope and data.
326
327
328.. method:: IMAP4.proxyauth(user)
329
330 Assume authentication as *user*. Allows an authorised administrator to proxy
331 into any user's mailbox.
332
Georg Brandl116aa622007-08-15 14:28:22 +0000333
334.. method:: IMAP4.read(size)
335
336 Reads *size* bytes from the remote server. You may override this method.
337
338
339.. method:: IMAP4.readline()
340
341 Reads one line from the remote server. You may override this method.
342
343
344.. method:: IMAP4.recent()
345
346 Prompt server for an update. Returned data is ``None`` if no new messages, else
347 value of ``RECENT`` response.
348
349
350.. method:: IMAP4.rename(oldmailbox, newmailbox)
351
352 Rename mailbox named *oldmailbox* to *newmailbox*.
353
354
355.. method:: IMAP4.response(code)
356
357 Return data for response *code* if received, or ``None``. Returns the given
358 code, instead of the usual type.
359
360
361.. method:: IMAP4.search(charset, criterion[, ...])
362
363 Search mailbox for matching messages. *charset* may be ``None``, in which case
364 no ``CHARSET`` will be specified in the request to the server. The IMAP
365 protocol requires that at least one criterion be specified; an exception will be
366 raised when the server returns an error.
367
368 Example::
369
370 # M is a connected IMAP4 instance...
371 typ, msgnums = M.search(None, 'FROM', '"LDJ"')
372
373 # or:
374 typ, msgnums = M.search(None, '(FROM "LDJ")')
375
376
Georg Brandl3dd33882009-06-01 17:35:27 +0000377.. method:: IMAP4.select(mailbox='INBOX', readonly=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379 Select a mailbox. Returned data is the count of messages in *mailbox*
380 (``EXISTS`` response). The default *mailbox* is ``'INBOX'``. If the *readonly*
381 flag is set, modifications to the mailbox are not allowed.
382
383
384.. method:: IMAP4.send(data)
385
386 Sends ``data`` to the remote server. You may override this method.
387
388
389.. method:: IMAP4.setacl(mailbox, who, what)
390
391 Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
392 the ``Cyrus`` server.
393
394
395.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])
396
397 Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
398 supported by the ``Cyrus`` server.
399
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401.. method:: IMAP4.setquota(root, limits)
402
403 Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
404 QUOTA extension defined in rfc2087.
405
Georg Brandl116aa622007-08-15 14:28:22 +0000406
407.. method:: IMAP4.shutdown()
408
Antoine Pitroufdded562011-02-07 15:58:11 +0000409 Close connection established in ``open``. This method is implicitly
410 called by :meth:`IMAP4.logout`. You may override this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000411
412
413.. method:: IMAP4.socket()
414
415 Returns socket instance used to connect to server.
416
417
418.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])
419
420 The ``sort`` command is a variant of ``search`` with sorting semantics for the
421 results. Returned data contains a space separated list of matching message
422 numbers.
423
424 Sort has two arguments before the *search_criterion* argument(s); a
425 parenthesized list of *sort_criteria*, and the searching *charset*. Note that
426 unlike ``search``, the searching *charset* argument is mandatory. There is also
427 a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
428 corresponds to ``search``. The ``sort`` command first searches the mailbox for
429 messages that match the given searching criteria using the charset argument for
430 the interpretation of strings in the searching criteria. It then returns the
431 numbers of matching messages.
432
433 This is an ``IMAP4rev1`` extension command.
434
435
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000436.. method:: IMAP4.starttls(ssl_context=None)
437
438 Send a ``STARTTLS`` command. The *ssl_context* argument is optional
439 and should be a :class:`ssl.SSLContext` object. This will enable
440 encryption on the IMAP connection.
441
442 .. versionadded:: 3.2
443
Christian Heimes48aae572013-12-02 20:01:29 +0100444 .. versionchanged:: 3.4
445 The method now supports hostname check with
446 :attr:`SSLContext.check_hostname` and *Server Name Indicator* (see
447 :data:`~ssl.HAS_SNI`).
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000448
Georg Brandl116aa622007-08-15 14:28:22 +0000449.. method:: IMAP4.status(mailbox, names)
450
451 Request named status conditions for *mailbox*.
452
453
454.. method:: IMAP4.store(message_set, command, flag_list)
455
456 Alters flag dispositions for messages in mailbox. *command* is specified by
457 section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
458 optionally with a suffix of ".SILENT".
459
460 For example, to set the delete flag on all messages::
461
462 typ, data = M.search(None, 'ALL')
463 for num in data[0].split():
464 M.store(num, '+FLAGS', '\\Deleted')
465 M.expunge()
466
467
468.. method:: IMAP4.subscribe(mailbox)
469
470 Subscribe to new mailbox.
471
472
473.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])
474
475 The ``thread`` command is a variant of ``search`` with threading semantics for
476 the results. Returned data contains a space separated list of thread members.
477
478 Thread members consist of zero or more messages numbers, delimited by spaces,
479 indicating successive parent and child.
480
481 Thread has two arguments before the *search_criterion* argument(s); a
482 *threading_algorithm*, and the searching *charset*. Note that unlike
483 ``search``, the searching *charset* argument is mandatory. There is also a
484 ``uid thread`` command which corresponds to ``thread`` the way that ``uid
485 search`` corresponds to ``search``. The ``thread`` command first searches the
486 mailbox for messages that match the given searching criteria using the charset
487 argument for the interpretation of strings in the searching criteria. It then
488 returns the matching messages threaded according to the specified threading
489 algorithm.
490
491 This is an ``IMAP4rev1`` extension command.
492
Georg Brandl116aa622007-08-15 14:28:22 +0000493
494.. method:: IMAP4.uid(command, arg[, ...])
495
496 Execute command args with messages identified by UID, rather than message
497 number. Returns response appropriate to command. At least one argument must be
498 supplied; if none are provided, the server will return an error and an exception
499 will be raised.
500
501
502.. method:: IMAP4.unsubscribe(mailbox)
503
504 Unsubscribe from old mailbox.
505
506
Georg Brandl3dd33882009-06-01 17:35:27 +0000507.. method:: IMAP4.xatom(name[, ...])
Georg Brandl116aa622007-08-15 14:28:22 +0000508
509 Allow simple extension commands notified by server in ``CAPABILITY`` response.
510
Georg Brandl116aa622007-08-15 14:28:22 +0000511
Georg Brandl3dd33882009-06-01 17:35:27 +0000512The following attributes are defined on instances of :class:`IMAP4`:
Georg Brandl116aa622007-08-15 14:28:22 +0000513
514.. attribute:: IMAP4.PROTOCOL_VERSION
515
516 The most recent supported protocol in the ``CAPABILITY`` response from the
517 server.
518
519
520.. attribute:: IMAP4.debug
521
522 Integer value to control debugging output. The initialize value is taken from
523 the module variable ``Debug``. Values greater than three trace each command.
524
525
526.. _imap4-example:
527
528IMAP4 Example
529-------------
530
531Here is a minimal example (without error checking) that opens a mailbox and
532retrieves and prints all messages::
533
534 import getpass, imaplib
535
536 M = imaplib.IMAP4()
537 M.login(getpass.getuser(), getpass.getpass())
538 M.select()
539 typ, data = M.search(None, 'ALL')
540 for num in data[0].split():
541 typ, data = M.fetch(num, '(RFC822)')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000542 print('Message %s\n%s\n' % (num, data[0][1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000543 M.close()
544 M.logout()
545