blob: 01236fbb8ea5ae7f676b184d27da78664bde90fd [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
Antoine Pitrouf3b001f2010-11-12 18:49:16 +000083
Georg Brandl116aa622007-08-15 14:28:22 +000084The second subclass allows for connections created by a child process:
85
86
87.. class:: IMAP4_stream(command)
88
89 This is a subclass derived from :class:`IMAP4` that connects to the
90 ``stdin/stdout`` file descriptors created by passing *command* to
Christian Heimesfb5faf02008-11-05 19:39:50 +000091 ``subprocess.Popen()``.
Georg Brandl116aa622007-08-15 14:28:22 +000092
Georg Brandl116aa622007-08-15 14:28:22 +000093
94The following utility functions are defined:
95
96
97.. function:: Internaldate2tuple(datestr)
98
Alexander Belopolsky41a99bc2011-01-19 19:53:30 +000099 Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
100 time. The return value is a :class:`time.struct_time` tuple or
101 None if the string has wrong format.
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103.. function:: Int2AP(num)
104
105 Converts an integer into a string representation using characters from the set
106 [``A`` .. ``P``].
107
108
109.. function:: ParseFlags(flagstr)
110
111 Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags.
112
113
114.. function:: Time2Internaldate(date_time)
115
Alexander Belopolsky8141cc72012-06-22 21:03:39 -0400116 Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation.
117 The return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS
118 +HHMM"`` (including double-quotes). The *date_time* argument can
119 be a number (int or float) representing seconds since epoch (as
120 returned by :func:`time.time`), a 9-tuple representing local time
121 an instance of :class:`time.struct_time` (as returned by
122 :func:`time.localtime`), an aware instance of
123 :class:`datetime.datetime`, or a double-quoted string. In the last
124 case, it is assumed to already be in the correct format.
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126Note that IMAP4 message numbers change as the mailbox changes; in particular,
127after an ``EXPUNGE`` command performs deletions the remaining messages are
128renumbered. So it is highly advisable to use UIDs instead, with the UID command.
129
130At the end of the module, there is a test section that contains a more extensive
131example of usage.
132
133
134.. seealso::
135
136 Documents describing the protocol, and sources and binaries for servers
137 implementing it, can all be found at the University of Washington's *IMAP
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000138 Information Center* (http://www.washington.edu/imap/).
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140
141.. _imap4-objects:
142
143IMAP4 Objects
144-------------
145
146All IMAP4rev1 commands are represented by methods of the same name, either
147upper-case or lower-case.
148
149All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
150and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If
151necessary (the string contains IMAP4 protocol-sensitive characters and isn't
152enclosed with either parentheses or double quotes) each string is quoted.
153However, the *password* argument to the ``LOGIN`` command is always quoted. If
154you want to avoid having an argument string quoted (eg: the *flags* argument to
155``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``).
156
157Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
158``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
159or mandated results from the command. Each *data* is either a string, or a
160tuple. If a tuple, then the first part is the header of the response, and the
161second part contains the data (ie: 'literal' value).
162
163The *message_set* options to commands below is a string specifying one or more
164messages to be acted upon. It may be a simple message number (``'1'``), a range
165of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
166commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite
167upper bound (``'3:*'``).
168
169An :class:`IMAP4` instance has the following methods:
170
171
172.. method:: IMAP4.append(mailbox, flags, date_time, message)
173
174 Append *message* to named mailbox.
175
176
177.. method:: IMAP4.authenticate(mechanism, authobject)
178
179 Authenticate command --- requires response processing.
180
181 *mechanism* specifies which authentication mechanism is to be used - it should
182 appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``.
183
184 *authobject* must be a callable object::
185
186 data = authobject(response)
187
R David Murray774a39f2013-02-19 12:17:31 -0500188 It will be called to process server continuation responses; the *response*
189 argument it is passed will be ``bytes``. It should return ``bytes`` *data*
190 that will be base64 encoded and sent to the server. It should return
191 ``None`` if the client abort response ``*`` should be sent instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000192
193
194.. method:: IMAP4.check()
195
196 Checkpoint mailbox on server.
197
198
199.. method:: IMAP4.close()
200
201 Close currently selected mailbox. Deleted messages are removed from writable
202 mailbox. This is the recommended command before ``LOGOUT``.
203
204
205.. method:: IMAP4.copy(message_set, new_mailbox)
206
207 Copy *message_set* messages onto end of *new_mailbox*.
208
209
210.. method:: IMAP4.create(mailbox)
211
212 Create new mailbox named *mailbox*.
213
214
215.. method:: IMAP4.delete(mailbox)
216
217 Delete old mailbox named *mailbox*.
218
219
220.. method:: IMAP4.deleteacl(mailbox, who)
221
222 Delete the ACLs (remove any rights) set for who on mailbox.
223
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225.. method:: IMAP4.expunge()
226
227 Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
228 response for each deleted message. Returned data contains a list of ``EXPUNGE``
229 message numbers in order received.
230
231
232.. method:: IMAP4.fetch(message_set, message_parts)
233
234 Fetch (parts of) messages. *message_parts* should be a string of message part
235 names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data
236 are tuples of message part envelope and data.
237
238
239.. method:: IMAP4.getacl(mailbox)
240
241 Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
242 by the ``Cyrus`` server.
243
244
245.. method:: IMAP4.getannotation(mailbox, entry, attribute)
246
247 Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
248 non-standard, but is supported by the ``Cyrus`` server.
249
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251.. method:: IMAP4.getquota(root)
252
253 Get the ``quota`` *root*'s resource usage and limits. This method is part of the
254 IMAP4 QUOTA extension defined in rfc2087.
255
Georg Brandl116aa622007-08-15 14:28:22 +0000256
257.. method:: IMAP4.getquotaroot(mailbox)
258
259 Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
260 of the IMAP4 QUOTA extension defined in rfc2087.
261
Georg Brandl116aa622007-08-15 14:28:22 +0000262
263.. method:: IMAP4.list([directory[, pattern]])
264
265 List mailbox names in *directory* matching *pattern*. *directory* defaults to
266 the top-level mail folder, and *pattern* defaults to match anything. Returned
267 data contains a list of ``LIST`` responses.
268
269
270.. method:: IMAP4.login(user, password)
271
272 Identify the client using a plaintext password. The *password* will be quoted.
273
274
275.. method:: IMAP4.login_cram_md5(user, password)
276
277 Force use of ``CRAM-MD5`` authentication when identifying the client to protect
278 the password. Will only work if the server ``CAPABILITY`` response includes the
279 phrase ``AUTH=CRAM-MD5``.
280
Georg Brandl116aa622007-08-15 14:28:22 +0000281
282.. method:: IMAP4.logout()
283
284 Shutdown connection to server. Returns server ``BYE`` response.
285
286
Georg Brandl3dd33882009-06-01 17:35:27 +0000287.. method:: IMAP4.lsub(directory='""', pattern='*')
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289 List subscribed mailbox names in directory matching pattern. *directory*
290 defaults to the top level directory and *pattern* defaults to match any mailbox.
291 Returned data are tuples of message part envelope and data.
292
293
294.. method:: IMAP4.myrights(mailbox)
295
296 Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
297
Georg Brandl116aa622007-08-15 14:28:22 +0000298
299.. method:: IMAP4.namespace()
300
301 Returns IMAP namespaces as defined in RFC2342.
302
Georg Brandl116aa622007-08-15 14:28:22 +0000303
304.. method:: IMAP4.noop()
305
306 Send ``NOOP`` to server.
307
308
309.. method:: IMAP4.open(host, port)
310
Antoine Pitroufdded562011-02-07 15:58:11 +0000311 Opens socket to *port* at *host*. This method is implicitly called by
312 the :class:`IMAP4` constructor. The connection objects established by this
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300313 method will be used in the :meth:`IMAP4.read`, :meth:`IMAP4.readline`,
314 :meth:`IMAP4.send`, and :meth:`IMAP4.shutdown` methods. You may override
315 this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000316
317
318.. method:: IMAP4.partial(message_num, message_part, start, length)
319
320 Fetch truncated part of a message. Returned data is a tuple of message part
321 envelope and data.
322
323
324.. method:: IMAP4.proxyauth(user)
325
326 Assume authentication as *user*. Allows an authorised administrator to proxy
327 into any user's mailbox.
328
Georg Brandl116aa622007-08-15 14:28:22 +0000329
330.. method:: IMAP4.read(size)
331
332 Reads *size* bytes from the remote server. You may override this method.
333
334
335.. method:: IMAP4.readline()
336
337 Reads one line from the remote server. You may override this method.
338
339
340.. method:: IMAP4.recent()
341
342 Prompt server for an update. Returned data is ``None`` if no new messages, else
343 value of ``RECENT`` response.
344
345
346.. method:: IMAP4.rename(oldmailbox, newmailbox)
347
348 Rename mailbox named *oldmailbox* to *newmailbox*.
349
350
351.. method:: IMAP4.response(code)
352
353 Return data for response *code* if received, or ``None``. Returns the given
354 code, instead of the usual type.
355
356
357.. method:: IMAP4.search(charset, criterion[, ...])
358
359 Search mailbox for matching messages. *charset* may be ``None``, in which case
360 no ``CHARSET`` will be specified in the request to the server. The IMAP
361 protocol requires that at least one criterion be specified; an exception will be
362 raised when the server returns an error.
363
364 Example::
365
366 # M is a connected IMAP4 instance...
367 typ, msgnums = M.search(None, 'FROM', '"LDJ"')
368
369 # or:
370 typ, msgnums = M.search(None, '(FROM "LDJ")')
371
372
Georg Brandl3dd33882009-06-01 17:35:27 +0000373.. method:: IMAP4.select(mailbox='INBOX', readonly=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000374
375 Select a mailbox. Returned data is the count of messages in *mailbox*
376 (``EXISTS`` response). The default *mailbox* is ``'INBOX'``. If the *readonly*
377 flag is set, modifications to the mailbox are not allowed.
378
379
380.. method:: IMAP4.send(data)
381
382 Sends ``data`` to the remote server. You may override this method.
383
384
385.. method:: IMAP4.setacl(mailbox, who, what)
386
387 Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
388 the ``Cyrus`` server.
389
390
391.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])
392
393 Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
394 supported by the ``Cyrus`` server.
395
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397.. method:: IMAP4.setquota(root, limits)
398
399 Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
400 QUOTA extension defined in rfc2087.
401
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403.. method:: IMAP4.shutdown()
404
Antoine Pitroufdded562011-02-07 15:58:11 +0000405 Close connection established in ``open``. This method is implicitly
406 called by :meth:`IMAP4.logout`. You may override this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000407
408
409.. method:: IMAP4.socket()
410
411 Returns socket instance used to connect to server.
412
413
414.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])
415
416 The ``sort`` command is a variant of ``search`` with sorting semantics for the
417 results. Returned data contains a space separated list of matching message
418 numbers.
419
420 Sort has two arguments before the *search_criterion* argument(s); a
421 parenthesized list of *sort_criteria*, and the searching *charset*. Note that
422 unlike ``search``, the searching *charset* argument is mandatory. There is also
423 a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
424 corresponds to ``search``. The ``sort`` command first searches the mailbox for
425 messages that match the given searching criteria using the charset argument for
426 the interpretation of strings in the searching criteria. It then returns the
427 numbers of matching messages.
428
429 This is an ``IMAP4rev1`` extension command.
430
431
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000432.. method:: IMAP4.starttls(ssl_context=None)
433
434 Send a ``STARTTLS`` command. The *ssl_context* argument is optional
435 and should be a :class:`ssl.SSLContext` object. This will enable
436 encryption on the IMAP connection.
437
438 .. versionadded:: 3.2
439
440
Georg Brandl116aa622007-08-15 14:28:22 +0000441.. method:: IMAP4.status(mailbox, names)
442
443 Request named status conditions for *mailbox*.
444
445
446.. method:: IMAP4.store(message_set, command, flag_list)
447
448 Alters flag dispositions for messages in mailbox. *command* is specified by
449 section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
450 optionally with a suffix of ".SILENT".
451
452 For example, to set the delete flag on all messages::
453
454 typ, data = M.search(None, 'ALL')
455 for num in data[0].split():
456 M.store(num, '+FLAGS', '\\Deleted')
457 M.expunge()
458
459
460.. method:: IMAP4.subscribe(mailbox)
461
462 Subscribe to new mailbox.
463
464
465.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])
466
467 The ``thread`` command is a variant of ``search`` with threading semantics for
468 the results. Returned data contains a space separated list of thread members.
469
470 Thread members consist of zero or more messages numbers, delimited by spaces,
471 indicating successive parent and child.
472
473 Thread has two arguments before the *search_criterion* argument(s); a
474 *threading_algorithm*, and the searching *charset*. Note that unlike
475 ``search``, the searching *charset* argument is mandatory. There is also a
476 ``uid thread`` command which corresponds to ``thread`` the way that ``uid
477 search`` corresponds to ``search``. The ``thread`` command first searches the
478 mailbox for messages that match the given searching criteria using the charset
479 argument for the interpretation of strings in the searching criteria. It then
480 returns the matching messages threaded according to the specified threading
481 algorithm.
482
483 This is an ``IMAP4rev1`` extension command.
484
Georg Brandl116aa622007-08-15 14:28:22 +0000485
486.. method:: IMAP4.uid(command, arg[, ...])
487
488 Execute command args with messages identified by UID, rather than message
489 number. Returns response appropriate to command. At least one argument must be
490 supplied; if none are provided, the server will return an error and an exception
491 will be raised.
492
493
494.. method:: IMAP4.unsubscribe(mailbox)
495
496 Unsubscribe from old mailbox.
497
498
Georg Brandl3dd33882009-06-01 17:35:27 +0000499.. method:: IMAP4.xatom(name[, ...])
Georg Brandl116aa622007-08-15 14:28:22 +0000500
501 Allow simple extension commands notified by server in ``CAPABILITY`` response.
502
Georg Brandl116aa622007-08-15 14:28:22 +0000503
Georg Brandl3dd33882009-06-01 17:35:27 +0000504The following attributes are defined on instances of :class:`IMAP4`:
Georg Brandl116aa622007-08-15 14:28:22 +0000505
506.. attribute:: IMAP4.PROTOCOL_VERSION
507
508 The most recent supported protocol in the ``CAPABILITY`` response from the
509 server.
510
511
512.. attribute:: IMAP4.debug
513
514 Integer value to control debugging output. The initialize value is taken from
515 the module variable ``Debug``. Values greater than three trace each command.
516
517
518.. _imap4-example:
519
520IMAP4 Example
521-------------
522
523Here is a minimal example (without error checking) that opens a mailbox and
524retrieves and prints all messages::
525
526 import getpass, imaplib
527
528 M = imaplib.IMAP4()
529 M.login(getpass.getuser(), getpass.getpass())
530 M.select()
531 typ, data = M.search(None, 'ALL')
532 for num in data[0].split():
533 typ, data = M.fetch(num, '(RFC822)')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000534 print('Message %s\n%s\n' % (num, data[0][1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000535 M.close()
536 M.logout()
537