blob: dab22e0bbb0b93259227e3db92ae1aaa3e24c094 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`imaplib` --- IMAP4 protocol client
3========================================
4
5.. module:: imaplib
6 :synopsis: IMAP4 protocol client (requires sockets).
7.. moduleauthor:: Piers Lauder <piers@communitysolutions.com.au>
8.. sectionauthor:: Piers Lauder <piers@communitysolutions.com.au>
9
10
11.. index::
12 pair: IMAP4; protocol
13 pair: IMAP4_SSL; protocol
14 pair: IMAP4_stream; protocol
15
16.. % Based on HTML documentation by Piers Lauder
17.. % <piers@communitysolutions.com.au>;
18.. % converted by Fred L. Drake, Jr. <fdrake@acm.org>.
19.. % Revised by ESR, January 2000.
20.. % Changes for IMAP4_SSL by Tino Lange <Tino.Lange@isg.de>, March 2002
21.. % Changes for IMAP4_stream by Piers Lauder
22.. % <piers@communitysolutions.com.au>, November 2002
23
24This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and
25:class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and
26implement a large subset of the IMAP4rev1 client protocol as defined in
27:rfc:`2060`. It is backward compatible with IMAP4 (:rfc:`1730`) servers, but
28note that the ``STATUS`` command is not supported in IMAP4.
29
30Three classes are provided by the :mod:`imaplib` module, :class:`IMAP4` is the
31base class:
32
33
34.. class:: IMAP4([host[, port]])
35
36 This class implements the actual IMAP4 protocol. The connection is created and
37 protocol version (IMAP4 or IMAP4rev1) is determined when the instance is
38 initialized. If *host* is not specified, ``''`` (the local host) is used. If
39 *port* is omitted, the standard IMAP4 port (143) is used.
40
41Three exceptions are defined as attributes of the :class:`IMAP4` class:
42
43
44.. exception:: IMAP4.error
45
46 Exception raised on any errors. The reason for the exception is passed to the
47 constructor as a string.
48
49
50.. exception:: IMAP4.abort
51
52 IMAP4 server errors cause this exception to be raised. This is a sub-class of
53 :exc:`IMAP4.error`. Note that closing the instance and instantiating a new one
54 will usually allow recovery from this exception.
55
56
57.. exception:: IMAP4.readonly
58
59 This exception is raised when a writable mailbox has its status changed by the
60 server. This is a sub-class of :exc:`IMAP4.error`. Some other client now has
61 write permission, and the mailbox will need to be re-opened to re-obtain write
62 permission.
63
64There's also a subclass for secure connections:
65
66
67.. class:: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])
68
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
74 and certificate chain file for the SSL connection.
75
76The second subclass allows for connections created by a child process:
77
78
79.. class:: IMAP4_stream(command)
80
81 This is a subclass derived from :class:`IMAP4` that connects to the
82 ``stdin/stdout`` file descriptors created by passing *command* to
83 ``os.popen2()``.
84
Georg Brandl116aa622007-08-15 14:28:22 +000085
86The following utility functions are defined:
87
88
89.. function:: Internaldate2tuple(datestr)
90
91 Converts an IMAP4 INTERNALDATE string to Coordinated Universal Time. Returns a
92 :mod:`time` module tuple.
93
94
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
108 Converts a :mod:`time` module tuple to an IMAP4 ``INTERNALDATE`` representation.
109 Returns a string in the form: ``"DD-Mmm-YYYY HH:MM:SS +HHMM"`` (including
110 double-quotes).
111
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
124 Information Center* (http://www.cac.washington.edu/imap/).
125
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
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210.. method:: IMAP4.expunge()
211
212 Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
213 response for each deleted message. Returned data contains a list of ``EXPUNGE``
214 message numbers in order received.
215
216
217.. method:: IMAP4.fetch(message_set, message_parts)
218
219 Fetch (parts of) messages. *message_parts* should be a string of message part
220 names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data
221 are tuples of message part envelope and data.
222
223
224.. method:: IMAP4.getacl(mailbox)
225
226 Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
227 by the ``Cyrus`` server.
228
229
230.. method:: IMAP4.getannotation(mailbox, entry, attribute)
231
232 Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
233 non-standard, but is supported by the ``Cyrus`` server.
234
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236.. method:: IMAP4.getquota(root)
237
238 Get the ``quota`` *root*'s resource usage and limits. This method is part of the
239 IMAP4 QUOTA extension defined in rfc2087.
240
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242.. method:: IMAP4.getquotaroot(mailbox)
243
244 Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
245 of the IMAP4 QUOTA extension defined in rfc2087.
246
Georg Brandl116aa622007-08-15 14:28:22 +0000247
248.. method:: IMAP4.list([directory[, pattern]])
249
250 List mailbox names in *directory* matching *pattern*. *directory* defaults to
251 the top-level mail folder, and *pattern* defaults to match anything. Returned
252 data contains a list of ``LIST`` responses.
253
254
255.. method:: IMAP4.login(user, password)
256
257 Identify the client using a plaintext password. The *password* will be quoted.
258
259
260.. method:: IMAP4.login_cram_md5(user, password)
261
262 Force use of ``CRAM-MD5`` authentication when identifying the client to protect
263 the password. Will only work if the server ``CAPABILITY`` response includes the
264 phrase ``AUTH=CRAM-MD5``.
265
Georg Brandl116aa622007-08-15 14:28:22 +0000266
267.. method:: IMAP4.logout()
268
269 Shutdown connection to server. Returns server ``BYE`` response.
270
271
272.. method:: IMAP4.lsub([directory[, pattern]])
273
274 List subscribed mailbox names in directory matching pattern. *directory*
275 defaults to the top level directory and *pattern* defaults to match any mailbox.
276 Returned data are tuples of message part envelope and data.
277
278
279.. method:: IMAP4.myrights(mailbox)
280
281 Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284.. method:: IMAP4.namespace()
285
286 Returns IMAP namespaces as defined in RFC2342.
287
Georg Brandl116aa622007-08-15 14:28:22 +0000288
289.. method:: IMAP4.noop()
290
291 Send ``NOOP`` to server.
292
293
294.. method:: IMAP4.open(host, port)
295
296 Opens socket to *port* at *host*. The connection objects established by this
297 method will be used in the ``read``, ``readline``, ``send``, and ``shutdown``
298 methods. You may override this method.
299
300
301.. method:: IMAP4.partial(message_num, message_part, start, length)
302
303 Fetch truncated part of a message. Returned data is a tuple of message part
304 envelope and data.
305
306
307.. method:: IMAP4.proxyauth(user)
308
309 Assume authentication as *user*. Allows an authorised administrator to proxy
310 into any user's mailbox.
311
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313.. method:: IMAP4.read(size)
314
315 Reads *size* bytes from the remote server. You may override this method.
316
317
318.. method:: IMAP4.readline()
319
320 Reads one line from the remote server. You may override this method.
321
322
323.. method:: IMAP4.recent()
324
325 Prompt server for an update. Returned data is ``None`` if no new messages, else
326 value of ``RECENT`` response.
327
328
329.. method:: IMAP4.rename(oldmailbox, newmailbox)
330
331 Rename mailbox named *oldmailbox* to *newmailbox*.
332
333
334.. method:: IMAP4.response(code)
335
336 Return data for response *code* if received, or ``None``. Returns the given
337 code, instead of the usual type.
338
339
340.. method:: IMAP4.search(charset, criterion[, ...])
341
342 Search mailbox for matching messages. *charset* may be ``None``, in which case
343 no ``CHARSET`` will be specified in the request to the server. The IMAP
344 protocol requires that at least one criterion be specified; an exception will be
345 raised when the server returns an error.
346
347 Example::
348
349 # M is a connected IMAP4 instance...
350 typ, msgnums = M.search(None, 'FROM', '"LDJ"')
351
352 # or:
353 typ, msgnums = M.search(None, '(FROM "LDJ")')
354
355
356.. method:: IMAP4.select([mailbox[, readonly]])
357
358 Select a mailbox. Returned data is the count of messages in *mailbox*
359 (``EXISTS`` response). The default *mailbox* is ``'INBOX'``. If the *readonly*
360 flag is set, modifications to the mailbox are not allowed.
361
362
363.. method:: IMAP4.send(data)
364
365 Sends ``data`` to the remote server. You may override this method.
366
367
368.. method:: IMAP4.setacl(mailbox, who, what)
369
370 Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
371 the ``Cyrus`` server.
372
373
374.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])
375
376 Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
377 supported by the ``Cyrus`` server.
378
Georg Brandl116aa622007-08-15 14:28:22 +0000379
380.. method:: IMAP4.setquota(root, limits)
381
382 Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
383 QUOTA extension defined in rfc2087.
384
Georg Brandl116aa622007-08-15 14:28:22 +0000385
386.. method:: IMAP4.shutdown()
387
388 Close connection established in ``open``. You may override this method.
389
390
391.. method:: IMAP4.socket()
392
393 Returns socket instance used to connect to server.
394
395
396.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])
397
398 The ``sort`` command is a variant of ``search`` with sorting semantics for the
399 results. Returned data contains a space separated list of matching message
400 numbers.
401
402 Sort has two arguments before the *search_criterion* argument(s); a
403 parenthesized list of *sort_criteria*, and the searching *charset*. Note that
404 unlike ``search``, the searching *charset* argument is mandatory. There is also
405 a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
406 corresponds to ``search``. The ``sort`` command first searches the mailbox for
407 messages that match the given searching criteria using the charset argument for
408 the interpretation of strings in the searching criteria. It then returns the
409 numbers of matching messages.
410
411 This is an ``IMAP4rev1`` extension command.
412
413
414.. method:: IMAP4.status(mailbox, names)
415
416 Request named status conditions for *mailbox*.
417
418
419.. method:: IMAP4.store(message_set, command, flag_list)
420
421 Alters flag dispositions for messages in mailbox. *command* is specified by
422 section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
423 optionally with a suffix of ".SILENT".
424
425 For example, to set the delete flag on all messages::
426
427 typ, data = M.search(None, 'ALL')
428 for num in data[0].split():
429 M.store(num, '+FLAGS', '\\Deleted')
430 M.expunge()
431
432
433.. method:: IMAP4.subscribe(mailbox)
434
435 Subscribe to new mailbox.
436
437
438.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])
439
440 The ``thread`` command is a variant of ``search`` with threading semantics for
441 the results. Returned data contains a space separated list of thread members.
442
443 Thread members consist of zero or more messages numbers, delimited by spaces,
444 indicating successive parent and child.
445
446 Thread has two arguments before the *search_criterion* argument(s); a
447 *threading_algorithm*, and the searching *charset*. Note that unlike
448 ``search``, the searching *charset* argument is mandatory. There is also a
449 ``uid thread`` command which corresponds to ``thread`` the way that ``uid
450 search`` corresponds to ``search``. The ``thread`` command first searches the
451 mailbox for messages that match the given searching criteria using the charset
452 argument for the interpretation of strings in the searching criteria. It then
453 returns the matching messages threaded according to the specified threading
454 algorithm.
455
456 This is an ``IMAP4rev1`` extension command.
457
Georg Brandl116aa622007-08-15 14:28:22 +0000458
459.. method:: IMAP4.uid(command, arg[, ...])
460
461 Execute command args with messages identified by UID, rather than message
462 number. Returns response appropriate to command. At least one argument must be
463 supplied; if none are provided, the server will return an error and an exception
464 will be raised.
465
466
467.. method:: IMAP4.unsubscribe(mailbox)
468
469 Unsubscribe from old mailbox.
470
471
472.. method:: IMAP4.xatom(name[, arg[, ...]])
473
474 Allow simple extension commands notified by server in ``CAPABILITY`` response.
475
476Instances of :class:`IMAP4_SSL` have just one additional method:
477
478
479.. method:: IMAP4_SSL.ssl()
480
481 Returns SSLObject instance used for the secure connection with the server.
482
483The following attributes are defined on instances of :class:`IMAP4`:
484
485
486.. attribute:: IMAP4.PROTOCOL_VERSION
487
488 The most recent supported protocol in the ``CAPABILITY`` response from the
489 server.
490
491
492.. attribute:: IMAP4.debug
493
494 Integer value to control debugging output. The initialize value is taken from
495 the module variable ``Debug``. Values greater than three trace each command.
496
497
498.. _imap4-example:
499
500IMAP4 Example
501-------------
502
503Here is a minimal example (without error checking) that opens a mailbox and
504retrieves and prints all messages::
505
506 import getpass, imaplib
507
508 M = imaplib.IMAP4()
509 M.login(getpass.getuser(), getpass.getpass())
510 M.select()
511 typ, data = M.search(None, 'ALL')
512 for num in data[0].split():
513 typ, data = M.fetch(num, '(RFC822)')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000514 print('Message %s\n%s\n' % (num, data[0][1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000515 M.close()
516 M.logout()
517