blob: 04088ac5aa519b80482a35b7197f832bc66e47c7 [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
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl3dd33882009-06-01 17:35:27 +000029.. class:: IMAP4(host='', port=IMAP4_PORT)
Georg Brandl116aa622007-08-15 14:28:22 +000030
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
Georg Brandl3dd33882009-06-01 17:35:27 +000062.. class:: IMAP4_SSL(host='', port=IMAP4_SSL_PORT, keyfile=None, certfile=None)
Georg Brandl116aa622007-08-15 14:28:22 +000063
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
Christian Heimesfb5faf02008-11-05 19:39:50 +000078 ``subprocess.Popen()``.
Georg Brandl116aa622007-08-15 14:28:22 +000079
Georg Brandl116aa622007-08-15 14:28:22 +000080
81The following utility functions are defined:
82
83
84.. function:: Internaldate2tuple(datestr)
85
86 Converts an IMAP4 INTERNALDATE string to Coordinated Universal Time. Returns a
87 :mod:`time` module tuple.
88
89
90.. function:: Int2AP(num)
91
92 Converts an integer into a string representation using characters from the set
93 [``A`` .. ``P``].
94
95
96.. function:: ParseFlags(flagstr)
97
98 Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags.
99
100
101.. function:: Time2Internaldate(date_time)
102
103 Converts a :mod:`time` module tuple to an IMAP4 ``INTERNALDATE`` representation.
104 Returns a string in the form: ``"DD-Mmm-YYYY HH:MM:SS +HHMM"`` (including
105 double-quotes).
106
107Note that IMAP4 message numbers change as the mailbox changes; in particular,
108after an ``EXPUNGE`` command performs deletions the remaining messages are
109renumbered. So it is highly advisable to use UIDs instead, with the UID command.
110
111At the end of the module, there is a test section that contains a more extensive
112example of usage.
113
114
115.. seealso::
116
117 Documents describing the protocol, and sources and binaries for servers
118 implementing it, can all be found at the University of Washington's *IMAP
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000119 Information Center* (http://www.washington.edu/imap/).
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121
122.. _imap4-objects:
123
124IMAP4 Objects
125-------------
126
127All IMAP4rev1 commands are represented by methods of the same name, either
128upper-case or lower-case.
129
130All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
131and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If
132necessary (the string contains IMAP4 protocol-sensitive characters and isn't
133enclosed with either parentheses or double quotes) each string is quoted.
134However, the *password* argument to the ``LOGIN`` command is always quoted. If
135you want to avoid having an argument string quoted (eg: the *flags* argument to
136``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``).
137
138Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
139``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
140or mandated results from the command. Each *data* is either a string, or a
141tuple. If a tuple, then the first part is the header of the response, and the
142second part contains the data (ie: 'literal' value).
143
144The *message_set* options to commands below is a string specifying one or more
145messages to be acted upon. It may be a simple message number (``'1'``), a range
146of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
147commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite
148upper bound (``'3:*'``).
149
150An :class:`IMAP4` instance has the following methods:
151
152
153.. method:: IMAP4.append(mailbox, flags, date_time, message)
154
155 Append *message* to named mailbox.
156
157
158.. method:: IMAP4.authenticate(mechanism, authobject)
159
160 Authenticate command --- requires response processing.
161
162 *mechanism* specifies which authentication mechanism is to be used - it should
163 appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``.
164
165 *authobject* must be a callable object::
166
167 data = authobject(response)
168
169 It will be called to process server continuation responses. It should return
170 ``data`` that will be encoded and sent to server. It should return ``None`` if
171 the client abort response ``*`` should be sent instead.
172
173
174.. method:: IMAP4.check()
175
176 Checkpoint mailbox on server.
177
178
179.. method:: IMAP4.close()
180
181 Close currently selected mailbox. Deleted messages are removed from writable
182 mailbox. This is the recommended command before ``LOGOUT``.
183
184
185.. method:: IMAP4.copy(message_set, new_mailbox)
186
187 Copy *message_set* messages onto end of *new_mailbox*.
188
189
190.. method:: IMAP4.create(mailbox)
191
192 Create new mailbox named *mailbox*.
193
194
195.. method:: IMAP4.delete(mailbox)
196
197 Delete old mailbox named *mailbox*.
198
199
200.. method:: IMAP4.deleteacl(mailbox, who)
201
202 Delete the ACLs (remove any rights) set for who on mailbox.
203
Georg Brandl116aa622007-08-15 14:28:22 +0000204
205.. method:: IMAP4.expunge()
206
207 Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
208 response for each deleted message. Returned data contains a list of ``EXPUNGE``
209 message numbers in order received.
210
211
212.. method:: IMAP4.fetch(message_set, message_parts)
213
214 Fetch (parts of) messages. *message_parts* should be a string of message part
215 names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data
216 are tuples of message part envelope and data.
217
218
219.. method:: IMAP4.getacl(mailbox)
220
221 Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
222 by the ``Cyrus`` server.
223
224
225.. method:: IMAP4.getannotation(mailbox, entry, attribute)
226
227 Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
228 non-standard, but is supported by the ``Cyrus`` server.
229
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231.. method:: IMAP4.getquota(root)
232
233 Get the ``quota`` *root*'s resource usage and limits. This method is part of the
234 IMAP4 QUOTA extension defined in rfc2087.
235
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. method:: IMAP4.getquotaroot(mailbox)
238
239 Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
240 of the IMAP4 QUOTA extension defined in rfc2087.
241
Georg Brandl116aa622007-08-15 14:28:22 +0000242
243.. method:: IMAP4.list([directory[, pattern]])
244
245 List mailbox names in *directory* matching *pattern*. *directory* defaults to
246 the top-level mail folder, and *pattern* defaults to match anything. Returned
247 data contains a list of ``LIST`` responses.
248
249
250.. method:: IMAP4.login(user, password)
251
252 Identify the client using a plaintext password. The *password* will be quoted.
253
254
255.. method:: IMAP4.login_cram_md5(user, password)
256
257 Force use of ``CRAM-MD5`` authentication when identifying the client to protect
258 the password. Will only work if the server ``CAPABILITY`` response includes the
259 phrase ``AUTH=CRAM-MD5``.
260
Georg Brandl116aa622007-08-15 14:28:22 +0000261
262.. method:: IMAP4.logout()
263
264 Shutdown connection to server. Returns server ``BYE`` response.
265
266
Georg Brandl3dd33882009-06-01 17:35:27 +0000267.. method:: IMAP4.lsub(directory='""', pattern='*')
Georg Brandl116aa622007-08-15 14:28:22 +0000268
269 List subscribed mailbox names in directory matching pattern. *directory*
270 defaults to the top level directory and *pattern* defaults to match any mailbox.
271 Returned data are tuples of message part envelope and data.
272
273
274.. method:: IMAP4.myrights(mailbox)
275
276 Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).
277
Georg Brandl116aa622007-08-15 14:28:22 +0000278
279.. method:: IMAP4.namespace()
280
281 Returns IMAP namespaces as defined in RFC2342.
282
Georg Brandl116aa622007-08-15 14:28:22 +0000283
284.. method:: IMAP4.noop()
285
286 Send ``NOOP`` to server.
287
288
289.. method:: IMAP4.open(host, port)
290
Antoine Pitroub248bdc2011-02-07 16:03:24 +0000291 Opens socket to *port* at *host*. This method is implicitly called by
292 the :class:`IMAP4` constructor. The connection objects established by this
Georg Brandl116aa622007-08-15 14:28:22 +0000293 method will be used in the ``read``, ``readline``, ``send``, and ``shutdown``
Antoine Pitroub248bdc2011-02-07 16:03:24 +0000294 methods. You may override this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296
297.. method:: IMAP4.partial(message_num, message_part, start, length)
298
299 Fetch truncated part of a message. Returned data is a tuple of message part
300 envelope and data.
301
302
303.. method:: IMAP4.proxyauth(user)
304
305 Assume authentication as *user*. Allows an authorised administrator to proxy
306 into any user's mailbox.
307
Georg Brandl116aa622007-08-15 14:28:22 +0000308
309.. method:: IMAP4.read(size)
310
311 Reads *size* bytes from the remote server. You may override this method.
312
313
314.. method:: IMAP4.readline()
315
316 Reads one line from the remote server. You may override this method.
317
318
319.. method:: IMAP4.recent()
320
321 Prompt server for an update. Returned data is ``None`` if no new messages, else
322 value of ``RECENT`` response.
323
324
325.. method:: IMAP4.rename(oldmailbox, newmailbox)
326
327 Rename mailbox named *oldmailbox* to *newmailbox*.
328
329
330.. method:: IMAP4.response(code)
331
332 Return data for response *code* if received, or ``None``. Returns the given
333 code, instead of the usual type.
334
335
336.. method:: IMAP4.search(charset, criterion[, ...])
337
338 Search mailbox for matching messages. *charset* may be ``None``, in which case
339 no ``CHARSET`` will be specified in the request to the server. The IMAP
340 protocol requires that at least one criterion be specified; an exception will be
341 raised when the server returns an error.
342
343 Example::
344
345 # M is a connected IMAP4 instance...
346 typ, msgnums = M.search(None, 'FROM', '"LDJ"')
347
348 # or:
349 typ, msgnums = M.search(None, '(FROM "LDJ")')
350
351
Georg Brandl3dd33882009-06-01 17:35:27 +0000352.. method:: IMAP4.select(mailbox='INBOX', readonly=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000353
354 Select a mailbox. Returned data is the count of messages in *mailbox*
355 (``EXISTS`` response). The default *mailbox* is ``'INBOX'``. If the *readonly*
356 flag is set, modifications to the mailbox are not allowed.
357
358
359.. method:: IMAP4.send(data)
360
361 Sends ``data`` to the remote server. You may override this method.
362
363
364.. method:: IMAP4.setacl(mailbox, who, what)
365
366 Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
367 the ``Cyrus`` server.
368
369
370.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])
371
372 Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
373 supported by the ``Cyrus`` server.
374
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376.. method:: IMAP4.setquota(root, limits)
377
378 Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
379 QUOTA extension defined in rfc2087.
380
Georg Brandl116aa622007-08-15 14:28:22 +0000381
382.. method:: IMAP4.shutdown()
383
Antoine Pitroub248bdc2011-02-07 16:03:24 +0000384 Close connection established in ``open``. This method is implicitly
385 called by :meth:`IMAP4.logout`. You may override this method.
Georg Brandl116aa622007-08-15 14:28:22 +0000386
387
388.. method:: IMAP4.socket()
389
390 Returns socket instance used to connect to server.
391
392
393.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])
394
395 The ``sort`` command is a variant of ``search`` with sorting semantics for the
396 results. Returned data contains a space separated list of matching message
397 numbers.
398
399 Sort has two arguments before the *search_criterion* argument(s); a
400 parenthesized list of *sort_criteria*, and the searching *charset*. Note that
401 unlike ``search``, the searching *charset* argument is mandatory. There is also
402 a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
403 corresponds to ``search``. The ``sort`` command first searches the mailbox for
404 messages that match the given searching criteria using the charset argument for
405 the interpretation of strings in the searching criteria. It then returns the
406 numbers of matching messages.
407
408 This is an ``IMAP4rev1`` extension command.
409
410
411.. method:: IMAP4.status(mailbox, names)
412
413 Request named status conditions for *mailbox*.
414
415
416.. method:: IMAP4.store(message_set, command, flag_list)
417
418 Alters flag dispositions for messages in mailbox. *command* is specified by
419 section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
420 optionally with a suffix of ".SILENT".
421
422 For example, to set the delete flag on all messages::
423
424 typ, data = M.search(None, 'ALL')
425 for num in data[0].split():
426 M.store(num, '+FLAGS', '\\Deleted')
427 M.expunge()
428
429
430.. method:: IMAP4.subscribe(mailbox)
431
432 Subscribe to new mailbox.
433
434
435.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])
436
437 The ``thread`` command is a variant of ``search`` with threading semantics for
438 the results. Returned data contains a space separated list of thread members.
439
440 Thread members consist of zero or more messages numbers, delimited by spaces,
441 indicating successive parent and child.
442
443 Thread has two arguments before the *search_criterion* argument(s); a
444 *threading_algorithm*, and the searching *charset*. Note that unlike
445 ``search``, the searching *charset* argument is mandatory. There is also a
446 ``uid thread`` command which corresponds to ``thread`` the way that ``uid
447 search`` corresponds to ``search``. The ``thread`` command first searches the
448 mailbox for messages that match the given searching criteria using the charset
449 argument for the interpretation of strings in the searching criteria. It then
450 returns the matching messages threaded according to the specified threading
451 algorithm.
452
453 This is an ``IMAP4rev1`` extension command.
454
Georg Brandl116aa622007-08-15 14:28:22 +0000455
456.. method:: IMAP4.uid(command, arg[, ...])
457
458 Execute command args with messages identified by UID, rather than message
459 number. Returns response appropriate to command. At least one argument must be
460 supplied; if none are provided, the server will return an error and an exception
461 will be raised.
462
463
464.. method:: IMAP4.unsubscribe(mailbox)
465
466 Unsubscribe from old mailbox.
467
468
Georg Brandl3dd33882009-06-01 17:35:27 +0000469.. method:: IMAP4.xatom(name[, ...])
Georg Brandl116aa622007-08-15 14:28:22 +0000470
471 Allow simple extension commands notified by server in ``CAPABILITY`` response.
472
Georg Brandl116aa622007-08-15 14:28:22 +0000473
Georg Brandl3dd33882009-06-01 17:35:27 +0000474The following attributes are defined on instances of :class:`IMAP4`:
Georg Brandl116aa622007-08-15 14:28:22 +0000475
476.. attribute:: IMAP4.PROTOCOL_VERSION
477
478 The most recent supported protocol in the ``CAPABILITY`` response from the
479 server.
480
481
482.. attribute:: IMAP4.debug
483
484 Integer value to control debugging output. The initialize value is taken from
485 the module variable ``Debug``. Values greater than three trace each command.
486
487
488.. _imap4-example:
489
490IMAP4 Example
491-------------
492
493Here is a minimal example (without error checking) that opens a mailbox and
494retrieves and prints all messages::
495
496 import getpass, imaplib
497
498 M = imaplib.IMAP4()
499 M.login(getpass.getuser(), getpass.getpass())
500 M.select()
501 typ, data = M.search(None, 'ALL')
502 for num in data[0].split():
503 typ, data = M.fetch(num, '(RFC822)')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000504 print('Message %s\n%s\n' % (num, data[0][1]))
Georg Brandl116aa622007-08-15 14:28:22 +0000505 M.close()
506 M.logout()
507