blob: f263bab9f02b103704510d2b9cb49a402dfc4a7c [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
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
42 :keyword:`with` statement exits. E.g.::
43
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
Antoine Pitrou08728162011-05-06 18:49:52 +020080.. class:: IMAP4_SSL(host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None, ssl_context=None)
Georg Brandl116aa622007-08-15 14:28:22 +000081
82 This is a subclass derived from :class:`IMAP4` that connects over an SSL
83 encrypted socket (to use this class you need a socket module that was compiled
84 with SSL support). If *host* is not specified, ``''`` (the local host) is used.
Antoine Pitrouc5e075f2014-03-22 18:19:11 +010085 If *port* is omitted, the standard IMAP4-over-SSL port (993) is used.
86 *ssl_context* is a :class:`ssl.SSLContext` object which allows bundling
87 SSL configuration options, certificates and private keys into a single
88 (potentially long-lived) structure. Please read :ref:`ssl-security` for
89 best practices.
90
91 *keyfile* and *certfile* are a legacy alternative to *ssl_context* - they
92 can point to PEM-formatted private key and certificate chain files for
93 the SSL connection. Note that the *keyfile*/*certfile* parameters are
94 mutually exclusive with *ssl_context*, a :class:`ValueError` is raised
95 if *keyfile*/*certfile* is provided along with *ssl_context*.
Antoine Pitrou08728162011-05-06 18:49:52 +020096
97 .. versionchanged:: 3.3
98 *ssl_context* parameter added.
Georg Brandl116aa622007-08-15 14:28:22 +000099
Christian Heimes48aae572013-12-02 20:01:29 +0100100 .. versionchanged:: 3.4
101 The class now supports hostname check with
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100102 :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
103 :data:`ssl.HAS_SNI`).
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000104
Georg Brandl116aa622007-08-15 14:28:22 +0000105The second subclass allows for connections created by a child process:
106
107
108.. class:: IMAP4_stream(command)
109
110 This is a subclass derived from :class:`IMAP4` that connects to the
111 ``stdin/stdout`` file descriptors created by passing *command* to
Christian Heimesfb5faf02008-11-05 19:39:50 +0000112 ``subprocess.Popen()``.
Georg Brandl116aa622007-08-15 14:28:22 +0000113
Georg Brandl116aa622007-08-15 14:28:22 +0000114
115The following utility functions are defined:
116
117
118.. function:: Internaldate2tuple(datestr)
119
Alexander Belopolsky41a99bc2011-01-19 19:53:30 +0000120 Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
121 time. The return value is a :class:`time.struct_time` tuple or
122 None if the string has wrong format.
Georg Brandl116aa622007-08-15 14:28:22 +0000123
124.. function:: Int2AP(num)
125
126 Converts an integer into a string representation using characters from the set
127 [``A`` .. ``P``].
128
129
130.. function:: ParseFlags(flagstr)
131
132 Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags.
133
134
135.. function:: Time2Internaldate(date_time)
136
Alexander Belopolsky8141cc72012-06-22 21:03:39 -0400137 Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation.
138 The return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS
139 +HHMM"`` (including double-quotes). The *date_time* argument can
140 be a number (int or float) representing seconds since epoch (as
141 returned by :func:`time.time`), a 9-tuple representing local time
142 an instance of :class:`time.struct_time` (as returned by
143 :func:`time.localtime`), an aware instance of
144 :class:`datetime.datetime`, or a double-quoted string. In the last
145 case, it is assumed to already be in the correct format.
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147Note that IMAP4 message numbers change as the mailbox changes; in particular,
148after an ``EXPUNGE`` command performs deletions the remaining messages are
149renumbered. So it is highly advisable to use UIDs instead, with the UID command.
150
151At the end of the module, there is a test section that contains a more extensive
152example of usage.
153
154
155.. seealso::
156
157 Documents describing the protocol, and sources and binaries for servers
158 implementing it, can all be found at the University of Washington's *IMAP
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000159 Information Center* (http://www.washington.edu/imap/).
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161
162.. _imap4-objects:
163
164IMAP4 Objects
165-------------
166
167All IMAP4rev1 commands are represented by methods of the same name, either
168upper-case or lower-case.
169
170All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
171and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If
172necessary (the string contains IMAP4 protocol-sensitive characters and isn't
173enclosed with either parentheses or double quotes) each string is quoted.
174However, the *password* argument to the ``LOGIN`` command is always quoted. If
175you want to avoid having an argument string quoted (eg: the *flags* argument to
176``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``).
177
178Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
179``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
180or mandated results from the command. Each *data* is either a string, or a
181tuple. If a tuple, then the first part is the header of the response, and the
182second part contains the data (ie: 'literal' value).
183
184The *message_set* options to commands below is a string specifying one or more
185messages to be acted upon. It may be a simple message number (``'1'``), a range
186of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
187commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite
188upper bound (``'3:*'``).
189
190An :class:`IMAP4` instance has the following methods:
191
192
193.. method:: IMAP4.append(mailbox, flags, date_time, message)
194
195 Append *message* to named mailbox.
196
197
198.. method:: IMAP4.authenticate(mechanism, authobject)
199
200 Authenticate command --- requires response processing.
201
202 *mechanism* specifies which authentication mechanism is to be used - it should
203 appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``.
204
205 *authobject* must be a callable object::
206
207 data = authobject(response)
208
R David Murray774a39f2013-02-19 12:17:31 -0500209 It will be called to process server continuation responses; the *response*
210 argument it is passed will be ``bytes``. It should return ``bytes`` *data*
211 that will be base64 encoded and sent to the server. It should return
212 ``None`` if the client abort response ``*`` should be sent instead.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
215.. method:: IMAP4.check()
216
217 Checkpoint mailbox on server.
218
219
220.. method:: IMAP4.close()
221
222 Close currently selected mailbox. Deleted messages are removed from writable
223 mailbox. This is the recommended command before ``LOGOUT``.
224
225
226.. method:: IMAP4.copy(message_set, new_mailbox)
227
228 Copy *message_set* messages onto end of *new_mailbox*.
229
230
231.. method:: IMAP4.create(mailbox)
232
233 Create new mailbox named *mailbox*.
234
235
236.. method:: IMAP4.delete(mailbox)
237
238 Delete old mailbox named *mailbox*.
239
240
241.. method:: IMAP4.deleteacl(mailbox, who)
242
243 Delete the ACLs (remove any rights) set for who on mailbox.
244
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246.. method:: IMAP4.expunge()
247
248 Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
249 response for each deleted message. Returned data contains a list of ``EXPUNGE``
250 message numbers in order received.
251
252
253.. method:: IMAP4.fetch(message_set, message_parts)
254
255 Fetch (parts of) messages. *message_parts* should be a string of message part
256 names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data
257 are tuples of message part envelope and data.
258
259
260.. method:: IMAP4.getacl(mailbox)
261
262 Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
263 by the ``Cyrus`` server.
264
265
266.. method:: IMAP4.getannotation(mailbox, entry, attribute)
267
268 Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
269 non-standard, but is supported by the ``Cyrus`` server.
270
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272.. method:: IMAP4.getquota(root)
273
274 Get the ``quota`` *root*'s resource usage and limits. This method is part of the
275 IMAP4 QUOTA extension defined in rfc2087.
276
Georg Brandl116aa622007-08-15 14:28:22 +0000277
278.. method:: IMAP4.getquotaroot(mailbox)
279
280 Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
281 of the IMAP4 QUOTA extension defined in rfc2087.
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284.. method:: IMAP4.list([directory[, pattern]])
285
286 List mailbox names in *directory* matching *pattern*. *directory* defaults to
287 the top-level mail folder, and *pattern* defaults to match anything. Returned
288 data contains a list of ``LIST`` responses.
289
290
291.. method:: IMAP4.login(user, password)
292
293 Identify the client using a plaintext password. The *password* will be quoted.
294
295
296.. method:: IMAP4.login_cram_md5(user, password)
297
298 Force use of ``CRAM-MD5`` authentication when identifying the client to protect
299 the password. Will only work if the server ``CAPABILITY`` response includes the
300 phrase ``AUTH=CRAM-MD5``.
301
Georg Brandl116aa622007-08-15 14:28:22 +0000302
303.. method:: IMAP4.logout()
304
305 Shutdown connection to server. Returns server ``BYE`` response.
306
307
Georg Brandl3dd33882009-06-01 17:35:27 +0000308.. method:: IMAP4.lsub(directory='""', pattern='*')
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310 List subscribed mailbox names in directory matching pattern. *directory*
311 defaults to the top level directory and *pattern* defaults to match any mailbox.
312 Returned data are tuples of message part envelope and data.
313
314
315.. method:: IMAP4.myrights(mailbox)
316
317 Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
318
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320.. method:: IMAP4.namespace()
321
322 Returns IMAP namespaces as defined in RFC2342.
323
Georg Brandl116aa622007-08-15 14:28:22 +0000324
325.. method:: IMAP4.noop()
326
327 Send ``NOOP`` to server.
328
329
330.. method:: IMAP4.open(host, port)
331
Antoine Pitroufdded562011-02-07 15:58:11 +0000332 Opens socket to *port* at *host*. This method is implicitly called by
333 the :class:`IMAP4` constructor. The connection objects established by this
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300334 method will be used in the :meth:`IMAP4.read`, :meth:`IMAP4.readline`,
335 :meth:`IMAP4.send`, and :meth:`IMAP4.shutdown` methods. You may override
336 this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338
339.. method:: IMAP4.partial(message_num, message_part, start, length)
340
341 Fetch truncated part of a message. Returned data is a tuple of message part
342 envelope and data.
343
344
345.. method:: IMAP4.proxyauth(user)
346
347 Assume authentication as *user*. Allows an authorised administrator to proxy
348 into any user's mailbox.
349
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351.. method:: IMAP4.read(size)
352
353 Reads *size* bytes from the remote server. You may override this method.
354
355
356.. method:: IMAP4.readline()
357
358 Reads one line from the remote server. You may override this method.
359
360
361.. method:: IMAP4.recent()
362
363 Prompt server for an update. Returned data is ``None`` if no new messages, else
364 value of ``RECENT`` response.
365
366
367.. method:: IMAP4.rename(oldmailbox, newmailbox)
368
369 Rename mailbox named *oldmailbox* to *newmailbox*.
370
371
372.. method:: IMAP4.response(code)
373
374 Return data for response *code* if received, or ``None``. Returns the given
375 code, instead of the usual type.
376
377
378.. method:: IMAP4.search(charset, criterion[, ...])
379
380 Search mailbox for matching messages. *charset* may be ``None``, in which case
381 no ``CHARSET`` will be specified in the request to the server. The IMAP
382 protocol requires that at least one criterion be specified; an exception will be
383 raised when the server returns an error.
384
385 Example::
386
387 # M is a connected IMAP4 instance...
388 typ, msgnums = M.search(None, 'FROM', '"LDJ"')
389
390 # or:
391 typ, msgnums = M.search(None, '(FROM "LDJ")')
392
393
Georg Brandl3dd33882009-06-01 17:35:27 +0000394.. method:: IMAP4.select(mailbox='INBOX', readonly=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000395
396 Select a mailbox. Returned data is the count of messages in *mailbox*
397 (``EXISTS`` response). The default *mailbox* is ``'INBOX'``. If the *readonly*
398 flag is set, modifications to the mailbox are not allowed.
399
400
401.. method:: IMAP4.send(data)
402
403 Sends ``data`` to the remote server. You may override this method.
404
405
406.. method:: IMAP4.setacl(mailbox, who, what)
407
408 Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
409 the ``Cyrus`` server.
410
411
412.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])
413
414 Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
415 supported by the ``Cyrus`` server.
416
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418.. method:: IMAP4.setquota(root, limits)
419
420 Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
421 QUOTA extension defined in rfc2087.
422
Georg Brandl116aa622007-08-15 14:28:22 +0000423
424.. method:: IMAP4.shutdown()
425
Antoine Pitroufdded562011-02-07 15:58:11 +0000426 Close connection established in ``open``. This method is implicitly
427 called by :meth:`IMAP4.logout`. You may override this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000428
429
430.. method:: IMAP4.socket()
431
432 Returns socket instance used to connect to server.
433
434
435.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])
436
437 The ``sort`` command is a variant of ``search`` with sorting semantics for the
438 results. Returned data contains a space separated list of matching message
439 numbers.
440
441 Sort has two arguments before the *search_criterion* argument(s); a
442 parenthesized list of *sort_criteria*, and the searching *charset*. Note that
443 unlike ``search``, the searching *charset* argument is mandatory. There is also
444 a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
445 corresponds to ``search``. The ``sort`` command first searches the mailbox for
446 messages that match the given searching criteria using the charset argument for
447 the interpretation of strings in the searching criteria. It then returns the
448 numbers of matching messages.
449
450 This is an ``IMAP4rev1`` extension command.
451
452
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000453.. method:: IMAP4.starttls(ssl_context=None)
454
455 Send a ``STARTTLS`` command. The *ssl_context* argument is optional
456 and should be a :class:`ssl.SSLContext` object. This will enable
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100457 encryption on the IMAP connection. Please read :ref:`ssl-security` for
458 best practices.
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000459
460 .. versionadded:: 3.2
461
Christian Heimes48aae572013-12-02 20:01:29 +0100462 .. versionchanged:: 3.4
463 The method now supports hostname check with
Antoine Pitrouc5e075f2014-03-22 18:19:11 +0100464 :attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see
465 :data:`ssl.HAS_SNI`).
Antoine Pitrouf3b001f2010-11-12 18:49:16 +0000466
Georg Brandldf48b972014-03-24 09:06:18 +0100467
Georg Brandl116aa622007-08-15 14:28:22 +0000468.. method:: IMAP4.status(mailbox, names)
469
470 Request named status conditions for *mailbox*.
471
472
473.. method:: IMAP4.store(message_set, command, flag_list)
474
475 Alters flag dispositions for messages in mailbox. *command* is specified by
476 section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
477 optionally with a suffix of ".SILENT".
478
479 For example, to set the delete flag on all messages::
480
481 typ, data = M.search(None, 'ALL')
482 for num in data[0].split():
483 M.store(num, '+FLAGS', '\\Deleted')
484 M.expunge()
485
486
487.. method:: IMAP4.subscribe(mailbox)
488
489 Subscribe to new mailbox.
490
491
492.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])
493
494 The ``thread`` command is a variant of ``search`` with threading semantics for
495 the results. Returned data contains a space separated list of thread members.
496
497 Thread members consist of zero or more messages numbers, delimited by spaces,
498 indicating successive parent and child.
499
500 Thread has two arguments before the *search_criterion* argument(s); a
501 *threading_algorithm*, and the searching *charset*. Note that unlike
502 ``search``, the searching *charset* argument is mandatory. There is also a
503 ``uid thread`` command which corresponds to ``thread`` the way that ``uid
504 search`` corresponds to ``search``. The ``thread`` command first searches the
505 mailbox for messages that match the given searching criteria using the charset
506 argument for the interpretation of strings in the searching criteria. It then
507 returns the matching messages threaded according to the specified threading
508 algorithm.
509
510 This is an ``IMAP4rev1`` extension command.
511
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513.. method:: IMAP4.uid(command, arg[, ...])
514
515 Execute command args with messages identified by UID, rather than message
516 number. Returns response appropriate to command. At least one argument must be
517 supplied; if none are provided, the server will return an error and an exception
518 will be raised.
519
520
521.. method:: IMAP4.unsubscribe(mailbox)
522
523 Unsubscribe from old mailbox.
524
525
Georg Brandl3dd33882009-06-01 17:35:27 +0000526.. method:: IMAP4.xatom(name[, ...])
Georg Brandl116aa622007-08-15 14:28:22 +0000527
528 Allow simple extension commands notified by server in ``CAPABILITY`` response.
529
Georg Brandl116aa622007-08-15 14:28:22 +0000530
Georg Brandl3dd33882009-06-01 17:35:27 +0000531The following attributes are defined on instances of :class:`IMAP4`:
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533.. attribute:: IMAP4.PROTOCOL_VERSION
534
535 The most recent supported protocol in the ``CAPABILITY`` response from the
536 server.
537
538
539.. attribute:: IMAP4.debug
540
541 Integer value to control debugging output. The initialize value is taken from
542 the module variable ``Debug``. Values greater than three trace each command.
543
544
545.. _imap4-example:
546
547IMAP4 Example
548-------------
549
550Here is a minimal example (without error checking) that opens a mailbox and
551retrieves and prints all messages::
552
553 import getpass, imaplib
554
555 M = imaplib.IMAP4()
556 M.login(getpass.getuser(), getpass.getpass())
557 M.select()
558 typ, data = M.search(None, 'ALL')
559 for num in data[0].split():
560 typ, data = M.fetch(num, '(RFC822)')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000561 print('Message %s\n%s\n' % (num, data[0][1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000562 M.close()
563 M.logout()
564