blob: ca18a9cf63a6050edbb3d6310a51e1cc6a931746 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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>
Georg Brandlb19be572007-12-29 10:57:00 +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 Brandl8ec7f652007-08-15 14:28:01 +000012
13
14.. index::
15 pair: IMAP4; protocol
16 pair: IMAP4_SSL; protocol
17 pair: IMAP4_stream; protocol
18
Éric Araujo29a0b572011-08-19 02:14:03 +020019**Source code:** :source:`Lib/imaplib.py`
20
21--------------
22
Georg Brandl8ec7f652007-08-15 14:28:01 +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
33.. class:: IMAP4([host[, port]])
34
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
63There's also a subclass for secure connections:
64
65
66.. class:: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
67
68 This is a subclass derived from :class:`IMAP4` that connects over an SSL
69 encrypted socket (to use this class you need a socket module that was compiled
70 with SSL support). If *host* is not specified, ``''`` (the local host) is used.
71 If *port* is omitted, the standard IMAP4-over-SSL port (993) is used. *keyfile*
72 and *certfile* are also optional - they can contain a PEM formatted private key
73 and certificate chain file for the SSL connection.
74
75The second subclass allows for connections created by a child process:
76
77
78.. class:: IMAP4_stream(command)
79
80 This is a subclass derived from :class:`IMAP4` that connects to the
81 ``stdin/stdout`` file descriptors created by passing *command* to
82 ``os.popen2()``.
83
84 .. versionadded:: 2.3
85
86The following utility functions are defined:
87
88
89.. function:: Internaldate2tuple(datestr)
90
Alexander Belopolsky7e8fbd22011-01-19 21:48:20 +000091 Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
92 time. The return value is a :class:`time.struct_time` instance or
93 None if the string has wrong format.
Georg Brandl8ec7f652007-08-15 14:28:01 +000094
95.. function:: Int2AP(num)
96
97 Converts an integer into a string representation using characters from the set
98 [``A`` .. ``P``].
99
100
101.. function:: ParseFlags(flagstr)
102
103 Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags.
104
105
106.. function:: Time2Internaldate(date_time)
107
Alexander Belopolsky7e8fbd22011-01-19 21:48:20 +0000108 Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation. The
109 return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS
110 +HHMM"`` (including double-quotes). The *date_time* argument can be a
Ezio Melottic2077b02011-03-16 12:34:31 +0200111 number (int or float) representing seconds since epoch (as returned
Alexander Belopolsky7e8fbd22011-01-19 21:48:20 +0000112 by :func:`time.time`), a 9-tuple representing local time (as returned by
113 :func:`time.localtime`), or a double-quoted string. In the last case, it
114 is assumed to already be in the correct format.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000115
116Note that IMAP4 message numbers change as the mailbox changes; in particular,
117after an ``EXPUNGE`` command performs deletions the remaining messages are
118renumbered. So it is highly advisable to use UIDs instead, with the UID command.
119
120At the end of the module, there is a test section that contains a more extensive
121example of usage.
122
123
124.. seealso::
125
126 Documents describing the protocol, and sources and binaries for servers
127 implementing it, can all be found at the University of Washington's *IMAP
Georg Brandl02677812008-03-15 00:20:19 +0000128 Information Center* (http://www.washington.edu/imap/).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000129
130
131.. _imap4-objects:
132
133IMAP4 Objects
134-------------
135
136All IMAP4rev1 commands are represented by methods of the same name, either
137upper-case or lower-case.
138
139All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
140and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If
141necessary (the string contains IMAP4 protocol-sensitive characters and isn't
142enclosed with either parentheses or double quotes) each string is quoted.
143However, the *password* argument to the ``LOGIN`` command is always quoted. If
144you want to avoid having an argument string quoted (eg: the *flags* argument to
145``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``).
146
147Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
148``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
149or mandated results from the command. Each *data* is either a string, or a
150tuple. If a tuple, then the first part is the header of the response, and the
151second part contains the data (ie: 'literal' value).
152
153The *message_set* options to commands below is a string specifying one or more
154messages to be acted upon. It may be a simple message number (``'1'``), a range
155of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
156commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite
157upper bound (``'3:*'``).
158
159An :class:`IMAP4` instance has the following methods:
160
161
162.. method:: IMAP4.append(mailbox, flags, date_time, message)
163
164 Append *message* to named mailbox.
165
166
167.. method:: IMAP4.authenticate(mechanism, authobject)
168
169 Authenticate command --- requires response processing.
170
171 *mechanism* specifies which authentication mechanism is to be used - it should
172 appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``.
173
174 *authobject* must be a callable object::
175
176 data = authobject(response)
177
178 It will be called to process server continuation responses. It should return
179 ``data`` that will be encoded and sent to server. It should return ``None`` if
180 the client abort response ``*`` should be sent instead.
181
182
183.. method:: IMAP4.check()
184
185 Checkpoint mailbox on server.
186
187
188.. method:: IMAP4.close()
189
190 Close currently selected mailbox. Deleted messages are removed from writable
191 mailbox. This is the recommended command before ``LOGOUT``.
192
193
194.. method:: IMAP4.copy(message_set, new_mailbox)
195
196 Copy *message_set* messages onto end of *new_mailbox*.
197
198
199.. method:: IMAP4.create(mailbox)
200
201 Create new mailbox named *mailbox*.
202
203
204.. method:: IMAP4.delete(mailbox)
205
206 Delete old mailbox named *mailbox*.
207
208
209.. method:: IMAP4.deleteacl(mailbox, who)
210
211 Delete the ACLs (remove any rights) set for who on mailbox.
212
213 .. versionadded:: 2.4
214
215
216.. method:: IMAP4.expunge()
217
218 Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
219 response for each deleted message. Returned data contains a list of ``EXPUNGE``
220 message numbers in order received.
221
222
223.. method:: IMAP4.fetch(message_set, message_parts)
224
225 Fetch (parts of) messages. *message_parts* should be a string of message part
226 names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data
227 are tuples of message part envelope and data.
228
229
230.. method:: IMAP4.getacl(mailbox)
231
232 Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
233 by the ``Cyrus`` server.
234
235
236.. method:: IMAP4.getannotation(mailbox, entry, attribute)
237
238 Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
239 non-standard, but is supported by the ``Cyrus`` server.
240
241 .. versionadded:: 2.5
242
243
244.. method:: IMAP4.getquota(root)
245
246 Get the ``quota`` *root*'s resource usage and limits. This method is part of the
247 IMAP4 QUOTA extension defined in rfc2087.
248
249 .. versionadded:: 2.3
250
251
252.. method:: IMAP4.getquotaroot(mailbox)
253
254 Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
255 of the IMAP4 QUOTA extension defined in rfc2087.
256
257 .. versionadded:: 2.3
258
259
260.. method:: IMAP4.list([directory[, pattern]])
261
262 List mailbox names in *directory* matching *pattern*. *directory* defaults to
263 the top-level mail folder, and *pattern* defaults to match anything. Returned
264 data contains a list of ``LIST`` responses.
265
266
267.. method:: IMAP4.login(user, password)
268
269 Identify the client using a plaintext password. The *password* will be quoted.
270
271
272.. method:: IMAP4.login_cram_md5(user, password)
273
274 Force use of ``CRAM-MD5`` authentication when identifying the client to protect
275 the password. Will only work if the server ``CAPABILITY`` response includes the
276 phrase ``AUTH=CRAM-MD5``.
277
278 .. versionadded:: 2.3
279
280
281.. method:: IMAP4.logout()
282
283 Shutdown connection to server. Returns server ``BYE`` response.
284
285
286.. method:: IMAP4.lsub([directory[, pattern]])
287
288 List subscribed mailbox names in directory matching pattern. *directory*
289 defaults to the top level directory and *pattern* defaults to match any mailbox.
290 Returned data are tuples of message part envelope and data.
291
292
293.. method:: IMAP4.myrights(mailbox)
294
295 Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
296
297 .. versionadded:: 2.4
298
299
300.. method:: IMAP4.namespace()
301
302 Returns IMAP namespaces as defined in RFC2342.
303
304 .. versionadded:: 2.3
305
306
307.. method:: IMAP4.noop()
308
309 Send ``NOOP`` to server.
310
311
312.. method:: IMAP4.open(host, port)
313
Antoine Pitroue9bd9db2011-02-07 16:03:47 +0000314 Opens socket to *port* at *host*. This method is implicitly called by
315 the :class:`IMAP4` constructor. The connection objects established by this
Serhiy Storchakab33336f2013-10-13 23:09:00 +0300316 method will be used in the :meth:`IMAP4.read`, :meth:`IMAP4.readline`,
317 :meth:`IMAP4.send`, and :meth:`IMAP4.shutdown` methods. You may override
318 this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000319
320
321.. method:: IMAP4.partial(message_num, message_part, start, length)
322
323 Fetch truncated part of a message. Returned data is a tuple of message part
324 envelope and data.
325
326
327.. method:: IMAP4.proxyauth(user)
328
329 Assume authentication as *user*. Allows an authorised administrator to proxy
330 into any user's mailbox.
331
332 .. versionadded:: 2.3
333
334
335.. method:: IMAP4.read(size)
336
337 Reads *size* bytes from the remote server. You may override this method.
338
339
340.. method:: IMAP4.readline()
341
342 Reads one line from the remote server. You may override this method.
343
344
345.. method:: IMAP4.recent()
346
347 Prompt server for an update. Returned data is ``None`` if no new messages, else
348 value of ``RECENT`` response.
349
350
351.. method:: IMAP4.rename(oldmailbox, newmailbox)
352
353 Rename mailbox named *oldmailbox* to *newmailbox*.
354
355
356.. method:: IMAP4.response(code)
357
358 Return data for response *code* if received, or ``None``. Returns the given
359 code, instead of the usual type.
360
361
362.. method:: IMAP4.search(charset, criterion[, ...])
363
364 Search mailbox for matching messages. *charset* may be ``None``, in which case
365 no ``CHARSET`` will be specified in the request to the server. The IMAP
366 protocol requires that at least one criterion be specified; an exception will be
367 raised when the server returns an error.
368
369 Example::
370
371 # M is a connected IMAP4 instance...
372 typ, msgnums = M.search(None, 'FROM', '"LDJ"')
373
374 # or:
375 typ, msgnums = M.search(None, '(FROM "LDJ")')
376
377
378.. method:: IMAP4.select([mailbox[, readonly]])
379
380 Select a mailbox. Returned data is the count of messages in *mailbox*
381 (``EXISTS`` response). The default *mailbox* is ``'INBOX'``. If the *readonly*
382 flag is set, modifications to the mailbox are not allowed.
383
384
385.. method:: IMAP4.send(data)
386
387 Sends ``data`` to the remote server. You may override this method.
388
389
390.. method:: IMAP4.setacl(mailbox, who, what)
391
392 Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
393 the ``Cyrus`` server.
394
395
396.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])
397
398 Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
399 supported by the ``Cyrus`` server.
400
401 .. versionadded:: 2.5
402
403
404.. method:: IMAP4.setquota(root, limits)
405
406 Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
407 QUOTA extension defined in rfc2087.
408
409 .. versionadded:: 2.3
410
411
412.. method:: IMAP4.shutdown()
413
Antoine Pitroue9bd9db2011-02-07 16:03:47 +0000414 Close connection established in ``open``. This method is implicitly
415 called by :meth:`IMAP4.logout`. You may override this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000416
417
418.. method:: IMAP4.socket()
419
420 Returns socket instance used to connect to server.
421
422
423.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])
424
425 The ``sort`` command is a variant of ``search`` with sorting semantics for the
426 results. Returned data contains a space separated list of matching message
427 numbers.
428
429 Sort has two arguments before the *search_criterion* argument(s); a
430 parenthesized list of *sort_criteria*, and the searching *charset*. Note that
431 unlike ``search``, the searching *charset* argument is mandatory. There is also
432 a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
433 corresponds to ``search``. The ``sort`` command first searches the mailbox for
434 messages that match the given searching criteria using the charset argument for
435 the interpretation of strings in the searching criteria. It then returns the
436 numbers of matching messages.
437
438 This is an ``IMAP4rev1`` extension command.
439
440
441.. 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
485 .. versionadded:: 2.4
486
487
488.. method:: IMAP4.uid(command, arg[, ...])
489
490 Execute command args with messages identified by UID, rather than message
491 number. Returns response appropriate to command. At least one argument must be
492 supplied; if none are provided, the server will return an error and an exception
493 will be raised.
494
495
496.. method:: IMAP4.unsubscribe(mailbox)
497
498 Unsubscribe from old mailbox.
499
500
501.. method:: IMAP4.xatom(name[, arg[, ...]])
502
503 Allow simple extension commands notified by server in ``CAPABILITY`` response.
504
505Instances of :class:`IMAP4_SSL` have just one additional method:
506
507
508.. method:: IMAP4_SSL.ssl()
509
510 Returns SSLObject instance used for the secure connection with the server.
511
512The following attributes are defined on instances of :class:`IMAP4`:
513
514
515.. attribute:: IMAP4.PROTOCOL_VERSION
516
517 The most recent supported protocol in the ``CAPABILITY`` response from the
518 server.
519
520
521.. attribute:: IMAP4.debug
522
523 Integer value to control debugging output. The initialize value is taken from
524 the module variable ``Debug``. Values greater than three trace each command.
525
526
527.. _imap4-example:
528
529IMAP4 Example
530-------------
531
532Here is a minimal example (without error checking) that opens a mailbox and
533retrieves and prints all messages::
534
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000535 import getpass, imaplib
Georg Brandl8ec7f652007-08-15 14:28:01 +0000536
537 M = imaplib.IMAP4()
538 M.login(getpass.getuser(), getpass.getpass())
539 M.select()
540 typ, data = M.search(None, 'ALL')
541 for num in data[0].split():
542 typ, data = M.fetch(num, '(RFC822)')
543 print 'Message %s\n%s\n' % (num, data[0][1])
544 M.close()
545 M.logout()
546