blob: 95bdc702e13dcab536b922e940028f66dbe034cf [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
Georg Brandl8ec7f652007-08-15 14:28:01 +000019This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and
20:class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and
21implement a large subset of the IMAP4rev1 client protocol as defined in
22:rfc:`2060`. It is backward compatible with IMAP4 (:rfc:`1730`) servers, but
23note that the ``STATUS`` command is not supported in IMAP4.
24
25Three classes are provided by the :mod:`imaplib` module, :class:`IMAP4` is the
26base class:
27
28
29.. class:: IMAP4([host[, port]])
30
31 This class implements the actual IMAP4 protocol. The connection is created and
32 protocol version (IMAP4 or IMAP4rev1) is determined when the instance is
33 initialized. If *host* is not specified, ``''`` (the local host) is used. If
34 *port* is omitted, the standard IMAP4 port (143) is used.
35
36Three exceptions are defined as attributes of the :class:`IMAP4` class:
37
38
39.. exception:: IMAP4.error
40
41 Exception raised on any errors. The reason for the exception is passed to the
42 constructor as a string.
43
44
45.. exception:: IMAP4.abort
46
47 IMAP4 server errors cause this exception to be raised. This is a sub-class of
48 :exc:`IMAP4.error`. Note that closing the instance and instantiating a new one
49 will usually allow recovery from this exception.
50
51
52.. exception:: IMAP4.readonly
53
54 This exception is raised when a writable mailbox has its status changed by the
55 server. This is a sub-class of :exc:`IMAP4.error`. Some other client now has
56 write permission, and the mailbox will need to be re-opened to re-obtain write
57 permission.
58
59There's also a subclass for secure connections:
60
61
62.. class:: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
63
64 This is a subclass derived from :class:`IMAP4` that connects over an SSL
65 encrypted socket (to use this class you need a socket module that was compiled
66 with SSL support). If *host* is not specified, ``''`` (the local host) is used.
67 If *port* is omitted, the standard IMAP4-over-SSL port (993) is used. *keyfile*
68 and *certfile* are also optional - they can contain a PEM formatted private key
69 and certificate chain file for the SSL connection.
70
71The second subclass allows for connections created by a child process:
72
73
74.. class:: IMAP4_stream(command)
75
76 This is a subclass derived from :class:`IMAP4` that connects to the
77 ``stdin/stdout`` file descriptors created by passing *command* to
78 ``os.popen2()``.
79
80 .. versionadded:: 2.3
81
82The following utility functions are defined:
83
84
85.. function:: Internaldate2tuple(datestr)
86
Alexander Belopolsky7e8fbd22011-01-19 21:48:20 +000087 Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
88 time. The return value is a :class:`time.struct_time` instance or
89 None if the string has wrong format.
Georg Brandl8ec7f652007-08-15 14:28:01 +000090
91.. function:: Int2AP(num)
92
93 Converts an integer into a string representation using characters from the set
94 [``A`` .. ``P``].
95
96
97.. function:: ParseFlags(flagstr)
98
99 Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags.
100
101
102.. function:: Time2Internaldate(date_time)
103
Alexander Belopolsky7e8fbd22011-01-19 21:48:20 +0000104 Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation. The
105 return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS
106 +HHMM"`` (including double-quotes). The *date_time* argument can be a
Ezio Melottic2077b02011-03-16 12:34:31 +0200107 number (int or float) representing seconds since epoch (as returned
Alexander Belopolsky7e8fbd22011-01-19 21:48:20 +0000108 by :func:`time.time`), a 9-tuple representing local time (as returned by
109 :func:`time.localtime`), or a double-quoted string. In the last case, it
110 is assumed to already be in the correct format.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000111
112Note that IMAP4 message numbers change as the mailbox changes; in particular,
113after an ``EXPUNGE`` command performs deletions the remaining messages are
114renumbered. So it is highly advisable to use UIDs instead, with the UID command.
115
116At the end of the module, there is a test section that contains a more extensive
117example of usage.
118
119
120.. seealso::
121
122 Documents describing the protocol, and sources and binaries for servers
123 implementing it, can all be found at the University of Washington's *IMAP
Georg Brandl02677812008-03-15 00:20:19 +0000124 Information Center* (http://www.washington.edu/imap/).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000125
126
127.. _imap4-objects:
128
129IMAP4 Objects
130-------------
131
132All IMAP4rev1 commands are represented by methods of the same name, either
133upper-case or lower-case.
134
135All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
136and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If
137necessary (the string contains IMAP4 protocol-sensitive characters and isn't
138enclosed with either parentheses or double quotes) each string is quoted.
139However, the *password* argument to the ``LOGIN`` command is always quoted. If
140you want to avoid having an argument string quoted (eg: the *flags* argument to
141``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``).
142
143Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
144``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
145or mandated results from the command. Each *data* is either a string, or a
146tuple. If a tuple, then the first part is the header of the response, and the
147second part contains the data (ie: 'literal' value).
148
149The *message_set* options to commands below is a string specifying one or more
150messages to be acted upon. It may be a simple message number (``'1'``), a range
151of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
152commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite
153upper bound (``'3:*'``).
154
155An :class:`IMAP4` instance has the following methods:
156
157
158.. method:: IMAP4.append(mailbox, flags, date_time, message)
159
160 Append *message* to named mailbox.
161
162
163.. method:: IMAP4.authenticate(mechanism, authobject)
164
165 Authenticate command --- requires response processing.
166
167 *mechanism* specifies which authentication mechanism is to be used - it should
168 appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``.
169
170 *authobject* must be a callable object::
171
172 data = authobject(response)
173
174 It will be called to process server continuation responses. It should return
175 ``data`` that will be encoded and sent to server. It should return ``None`` if
176 the client abort response ``*`` should be sent instead.
177
178
179.. method:: IMAP4.check()
180
181 Checkpoint mailbox on server.
182
183
184.. method:: IMAP4.close()
185
186 Close currently selected mailbox. Deleted messages are removed from writable
187 mailbox. This is the recommended command before ``LOGOUT``.
188
189
190.. method:: IMAP4.copy(message_set, new_mailbox)
191
192 Copy *message_set* messages onto end of *new_mailbox*.
193
194
195.. method:: IMAP4.create(mailbox)
196
197 Create new mailbox named *mailbox*.
198
199
200.. method:: IMAP4.delete(mailbox)
201
202 Delete old mailbox named *mailbox*.
203
204
205.. method:: IMAP4.deleteacl(mailbox, who)
206
207 Delete the ACLs (remove any rights) set for who on mailbox.
208
209 .. versionadded:: 2.4
210
211
212.. method:: IMAP4.expunge()
213
214 Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
215 response for each deleted message. Returned data contains a list of ``EXPUNGE``
216 message numbers in order received.
217
218
219.. method:: IMAP4.fetch(message_set, message_parts)
220
221 Fetch (parts of) messages. *message_parts* should be a string of message part
222 names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data
223 are tuples of message part envelope and data.
224
225
226.. method:: IMAP4.getacl(mailbox)
227
228 Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
229 by the ``Cyrus`` server.
230
231
232.. method:: IMAP4.getannotation(mailbox, entry, attribute)
233
234 Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
235 non-standard, but is supported by the ``Cyrus`` server.
236
237 .. versionadded:: 2.5
238
239
240.. method:: IMAP4.getquota(root)
241
242 Get the ``quota`` *root*'s resource usage and limits. This method is part of the
243 IMAP4 QUOTA extension defined in rfc2087.
244
245 .. versionadded:: 2.3
246
247
248.. method:: IMAP4.getquotaroot(mailbox)
249
250 Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
251 of the IMAP4 QUOTA extension defined in rfc2087.
252
253 .. versionadded:: 2.3
254
255
256.. method:: IMAP4.list([directory[, pattern]])
257
258 List mailbox names in *directory* matching *pattern*. *directory* defaults to
259 the top-level mail folder, and *pattern* defaults to match anything. Returned
260 data contains a list of ``LIST`` responses.
261
262
263.. method:: IMAP4.login(user, password)
264
265 Identify the client using a plaintext password. The *password* will be quoted.
266
267
268.. method:: IMAP4.login_cram_md5(user, password)
269
270 Force use of ``CRAM-MD5`` authentication when identifying the client to protect
271 the password. Will only work if the server ``CAPABILITY`` response includes the
272 phrase ``AUTH=CRAM-MD5``.
273
274 .. versionadded:: 2.3
275
276
277.. method:: IMAP4.logout()
278
279 Shutdown connection to server. Returns server ``BYE`` response.
280
281
282.. method:: IMAP4.lsub([directory[, pattern]])
283
284 List subscribed mailbox names in directory matching pattern. *directory*
285 defaults to the top level directory and *pattern* defaults to match any mailbox.
286 Returned data are tuples of message part envelope and data.
287
288
289.. method:: IMAP4.myrights(mailbox)
290
291 Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
292
293 .. versionadded:: 2.4
294
295
296.. method:: IMAP4.namespace()
297
298 Returns IMAP namespaces as defined in RFC2342.
299
300 .. versionadded:: 2.3
301
302
303.. method:: IMAP4.noop()
304
305 Send ``NOOP`` to server.
306
307
308.. method:: IMAP4.open(host, port)
309
Antoine Pitroue9bd9db2011-02-07 16:03:47 +0000310 Opens socket to *port* at *host*. This method is implicitly called by
311 the :class:`IMAP4` constructor. The connection objects established by this
Georg Brandl8ec7f652007-08-15 14:28:01 +0000312 method will be used in the ``read``, ``readline``, ``send``, and ``shutdown``
Antoine Pitroue9bd9db2011-02-07 16:03:47 +0000313 methods. You may override this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000314
315
316.. method:: IMAP4.partial(message_num, message_part, start, length)
317
318 Fetch truncated part of a message. Returned data is a tuple of message part
319 envelope and data.
320
321
322.. method:: IMAP4.proxyauth(user)
323
324 Assume authentication as *user*. Allows an authorised administrator to proxy
325 into any user's mailbox.
326
327 .. versionadded:: 2.3
328
329
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
373.. method:: IMAP4.select([mailbox[, readonly]])
374
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
396 .. versionadded:: 2.5
397
398
399.. method:: IMAP4.setquota(root, limits)
400
401 Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
402 QUOTA extension defined in rfc2087.
403
404 .. versionadded:: 2.3
405
406
407.. method:: IMAP4.shutdown()
408
Antoine Pitroue9bd9db2011-02-07 16:03:47 +0000409 Close connection established in ``open``. This method is implicitly
410 called by :meth:`IMAP4.logout`. You may override this method.
Georg Brandl8ec7f652007-08-15 14:28:01 +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
436.. method:: IMAP4.status(mailbox, names)
437
438 Request named status conditions for *mailbox*.
439
440
441.. method:: IMAP4.store(message_set, command, flag_list)
442
443 Alters flag dispositions for messages in mailbox. *command* is specified by
444 section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
445 optionally with a suffix of ".SILENT".
446
447 For example, to set the delete flag on all messages::
448
449 typ, data = M.search(None, 'ALL')
450 for num in data[0].split():
451 M.store(num, '+FLAGS', '\\Deleted')
452 M.expunge()
453
454
455.. method:: IMAP4.subscribe(mailbox)
456
457 Subscribe to new mailbox.
458
459
460.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])
461
462 The ``thread`` command is a variant of ``search`` with threading semantics for
463 the results. Returned data contains a space separated list of thread members.
464
465 Thread members consist of zero or more messages numbers, delimited by spaces,
466 indicating successive parent and child.
467
468 Thread has two arguments before the *search_criterion* argument(s); a
469 *threading_algorithm*, and the searching *charset*. Note that unlike
470 ``search``, the searching *charset* argument is mandatory. There is also a
471 ``uid thread`` command which corresponds to ``thread`` the way that ``uid
472 search`` corresponds to ``search``. The ``thread`` command first searches the
473 mailbox for messages that match the given searching criteria using the charset
474 argument for the interpretation of strings in the searching criteria. It then
475 returns the matching messages threaded according to the specified threading
476 algorithm.
477
478 This is an ``IMAP4rev1`` extension command.
479
480 .. versionadded:: 2.4
481
482
483.. method:: IMAP4.uid(command, arg[, ...])
484
485 Execute command args with messages identified by UID, rather than message
486 number. Returns response appropriate to command. At least one argument must be
487 supplied; if none are provided, the server will return an error and an exception
488 will be raised.
489
490
491.. method:: IMAP4.unsubscribe(mailbox)
492
493 Unsubscribe from old mailbox.
494
495
496.. method:: IMAP4.xatom(name[, arg[, ...]])
497
498 Allow simple extension commands notified by server in ``CAPABILITY`` response.
499
500Instances of :class:`IMAP4_SSL` have just one additional method:
501
502
503.. method:: IMAP4_SSL.ssl()
504
505 Returns SSLObject instance used for the secure connection with the server.
506
507The following attributes are defined on instances of :class:`IMAP4`:
508
509
510.. attribute:: IMAP4.PROTOCOL_VERSION
511
512 The most recent supported protocol in the ``CAPABILITY`` response from the
513 server.
514
515
516.. attribute:: IMAP4.debug
517
518 Integer value to control debugging output. The initialize value is taken from
519 the module variable ``Debug``. Values greater than three trace each command.
520
521
522.. _imap4-example:
523
524IMAP4 Example
525-------------
526
527Here is a minimal example (without error checking) that opens a mailbox and
528retrieves and prints all messages::
529
Benjamin Petersona7b55a32009-02-20 03:31:23 +0000530 import getpass, imaplib
Georg Brandl8ec7f652007-08-15 14:28:01 +0000531
532 M = imaplib.IMAP4()
533 M.login(getpass.getuser(), getpass.getpass())
534 M.select()
535 typ, data = M.search(None, 'ALL')
536 for num in data[0].split():
537 typ, data = M.fetch(num, '(RFC822)')
538 print 'Message %s\n%s\n' % (num, data[0][1])
539 M.close()
540 M.logout()
541