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