Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame^] | 1 | |
| 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 | |
| 24 | This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and |
| 25 | :class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and |
| 26 | implement a large subset of the IMAP4rev1 client protocol as defined in |
| 27 | :rfc:`2060`. It is backward compatible with IMAP4 (:rfc:`1730`) servers, but |
| 28 | note that the ``STATUS`` command is not supported in IMAP4. |
| 29 | |
| 30 | Three classes are provided by the :mod:`imaplib` module, :class:`IMAP4` is the |
| 31 | base 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 | |
| 41 | Three 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 | |
| 64 | There'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 | |
| 76 | The 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 | |
| 85 | .. versionadded:: 2.3 |
| 86 | |
| 87 | The following utility functions are defined: |
| 88 | |
| 89 | |
| 90 | .. function:: Internaldate2tuple(datestr) |
| 91 | |
| 92 | Converts an IMAP4 INTERNALDATE string to Coordinated Universal Time. Returns a |
| 93 | :mod:`time` module tuple. |
| 94 | |
| 95 | |
| 96 | .. function:: Int2AP(num) |
| 97 | |
| 98 | Converts an integer into a string representation using characters from the set |
| 99 | [``A`` .. ``P``]. |
| 100 | |
| 101 | |
| 102 | .. function:: ParseFlags(flagstr) |
| 103 | |
| 104 | Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags. |
| 105 | |
| 106 | |
| 107 | .. function:: Time2Internaldate(date_time) |
| 108 | |
| 109 | Converts a :mod:`time` module tuple to an IMAP4 ``INTERNALDATE`` representation. |
| 110 | Returns a string in the form: ``"DD-Mmm-YYYY HH:MM:SS +HHMM"`` (including |
| 111 | double-quotes). |
| 112 | |
| 113 | Note that IMAP4 message numbers change as the mailbox changes; in particular, |
| 114 | after an ``EXPUNGE`` command performs deletions the remaining messages are |
| 115 | renumbered. So it is highly advisable to use UIDs instead, with the UID command. |
| 116 | |
| 117 | At the end of the module, there is a test section that contains a more extensive |
| 118 | example 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 |
| 125 | Information Center* (http://www.cac.washington.edu/imap/). |
| 126 | |
| 127 | |
| 128 | .. _imap4-objects: |
| 129 | |
| 130 | IMAP4 Objects |
| 131 | ------------- |
| 132 | |
| 133 | All IMAP4rev1 commands are represented by methods of the same name, either |
| 134 | upper-case or lower-case. |
| 135 | |
| 136 | All arguments to commands are converted to strings, except for ``AUTHENTICATE``, |
| 137 | and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If |
| 138 | necessary (the string contains IMAP4 protocol-sensitive characters and isn't |
| 139 | enclosed with either parentheses or double quotes) each string is quoted. |
| 140 | However, the *password* argument to the ``LOGIN`` command is always quoted. If |
| 141 | you 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 | |
| 144 | Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually |
| 145 | ``'OK'`` or ``'NO'``, and *data* is either the text from the command response, |
| 146 | or mandated results from the command. Each *data* is either a string, or a |
| 147 | tuple. If a tuple, then the first part is the header of the response, and the |
| 148 | second part contains the data (ie: 'literal' value). |
| 149 | |
| 150 | The *message_set* options to commands below is a string specifying one or more |
| 151 | messages to be acted upon. It may be a simple message number (``'1'``), a range |
| 152 | of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by |
| 153 | commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite |
| 154 | upper bound (``'3:*'``). |
| 155 | |
| 156 | An :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 | |
| 210 | .. versionadded:: 2.4 |
| 211 | |
| 212 | |
| 213 | .. method:: IMAP4.expunge() |
| 214 | |
| 215 | Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE`` |
| 216 | response for each deleted message. Returned data contains a list of ``EXPUNGE`` |
| 217 | message numbers in order received. |
| 218 | |
| 219 | |
| 220 | .. method:: IMAP4.fetch(message_set, message_parts) |
| 221 | |
| 222 | Fetch (parts of) messages. *message_parts* should be a string of message part |
| 223 | names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data |
| 224 | are tuples of message part envelope and data. |
| 225 | |
| 226 | |
| 227 | .. method:: IMAP4.getacl(mailbox) |
| 228 | |
| 229 | Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported |
| 230 | by the ``Cyrus`` server. |
| 231 | |
| 232 | |
| 233 | .. method:: IMAP4.getannotation(mailbox, entry, attribute) |
| 234 | |
| 235 | Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is |
| 236 | non-standard, but is supported by the ``Cyrus`` server. |
| 237 | |
| 238 | .. versionadded:: 2.5 |
| 239 | |
| 240 | |
| 241 | .. method:: IMAP4.getquota(root) |
| 242 | |
| 243 | Get the ``quota`` *root*'s resource usage and limits. This method is part of the |
| 244 | IMAP4 QUOTA extension defined in rfc2087. |
| 245 | |
| 246 | .. versionadded:: 2.3 |
| 247 | |
| 248 | |
| 249 | .. method:: IMAP4.getquotaroot(mailbox) |
| 250 | |
| 251 | Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part |
| 252 | of the IMAP4 QUOTA extension defined in rfc2087. |
| 253 | |
| 254 | .. versionadded:: 2.3 |
| 255 | |
| 256 | |
| 257 | .. method:: IMAP4.list([directory[, pattern]]) |
| 258 | |
| 259 | List mailbox names in *directory* matching *pattern*. *directory* defaults to |
| 260 | the top-level mail folder, and *pattern* defaults to match anything. Returned |
| 261 | data contains a list of ``LIST`` responses. |
| 262 | |
| 263 | |
| 264 | .. method:: IMAP4.login(user, password) |
| 265 | |
| 266 | Identify the client using a plaintext password. The *password* will be quoted. |
| 267 | |
| 268 | |
| 269 | .. method:: IMAP4.login_cram_md5(user, password) |
| 270 | |
| 271 | Force use of ``CRAM-MD5`` authentication when identifying the client to protect |
| 272 | the password. Will only work if the server ``CAPABILITY`` response includes the |
| 273 | phrase ``AUTH=CRAM-MD5``. |
| 274 | |
| 275 | .. versionadded:: 2.3 |
| 276 | |
| 277 | |
| 278 | .. method:: IMAP4.logout() |
| 279 | |
| 280 | Shutdown connection to server. Returns server ``BYE`` response. |
| 281 | |
| 282 | |
| 283 | .. method:: IMAP4.lsub([directory[, pattern]]) |
| 284 | |
| 285 | List subscribed mailbox names in directory matching pattern. *directory* |
| 286 | defaults to the top level directory and *pattern* defaults to match any mailbox. |
| 287 | Returned data are tuples of message part envelope and data. |
| 288 | |
| 289 | |
| 290 | .. method:: IMAP4.myrights(mailbox) |
| 291 | |
| 292 | Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). |
| 293 | |
| 294 | .. versionadded:: 2.4 |
| 295 | |
| 296 | |
| 297 | .. method:: IMAP4.namespace() |
| 298 | |
| 299 | Returns IMAP namespaces as defined in RFC2342. |
| 300 | |
| 301 | .. versionadded:: 2.3 |
| 302 | |
| 303 | |
| 304 | .. method:: IMAP4.noop() |
| 305 | |
| 306 | Send ``NOOP`` to server. |
| 307 | |
| 308 | |
| 309 | .. method:: IMAP4.open(host, port) |
| 310 | |
| 311 | Opens socket to *port* at *host*. The connection objects established by this |
| 312 | method will be used in the ``read``, ``readline``, ``send``, and ``shutdown`` |
| 313 | methods. You may override this method. |
| 314 | |
| 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 | |
| 409 | Close connection established in ``open``. You may override this method. |
| 410 | |
| 411 | |
| 412 | .. method:: IMAP4.socket() |
| 413 | |
| 414 | Returns socket instance used to connect to server. |
| 415 | |
| 416 | |
| 417 | .. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...]) |
| 418 | |
| 419 | The ``sort`` command is a variant of ``search`` with sorting semantics for the |
| 420 | results. Returned data contains a space separated list of matching message |
| 421 | numbers. |
| 422 | |
| 423 | Sort has two arguments before the *search_criterion* argument(s); a |
| 424 | parenthesized list of *sort_criteria*, and the searching *charset*. Note that |
| 425 | unlike ``search``, the searching *charset* argument is mandatory. There is also |
| 426 | a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search`` |
| 427 | corresponds to ``search``. The ``sort`` command first searches the mailbox for |
| 428 | messages that match the given searching criteria using the charset argument for |
| 429 | the interpretation of strings in the searching criteria. It then returns the |
| 430 | numbers of matching messages. |
| 431 | |
| 432 | This is an ``IMAP4rev1`` extension command. |
| 433 | |
| 434 | |
| 435 | .. method:: IMAP4.status(mailbox, names) |
| 436 | |
| 437 | Request named status conditions for *mailbox*. |
| 438 | |
| 439 | |
| 440 | .. method:: IMAP4.store(message_set, command, flag_list) |
| 441 | |
| 442 | Alters flag dispositions for messages in mailbox. *command* is specified by |
| 443 | section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS", |
| 444 | optionally with a suffix of ".SILENT". |
| 445 | |
| 446 | For example, to set the delete flag on all messages:: |
| 447 | |
| 448 | typ, data = M.search(None, 'ALL') |
| 449 | for num in data[0].split(): |
| 450 | M.store(num, '+FLAGS', '\\Deleted') |
| 451 | M.expunge() |
| 452 | |
| 453 | |
| 454 | .. method:: IMAP4.subscribe(mailbox) |
| 455 | |
| 456 | Subscribe to new mailbox. |
| 457 | |
| 458 | |
| 459 | .. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...]) |
| 460 | |
| 461 | The ``thread`` command is a variant of ``search`` with threading semantics for |
| 462 | the results. Returned data contains a space separated list of thread members. |
| 463 | |
| 464 | Thread members consist of zero or more messages numbers, delimited by spaces, |
| 465 | indicating successive parent and child. |
| 466 | |
| 467 | Thread has two arguments before the *search_criterion* argument(s); a |
| 468 | *threading_algorithm*, and the searching *charset*. Note that unlike |
| 469 | ``search``, the searching *charset* argument is mandatory. There is also a |
| 470 | ``uid thread`` command which corresponds to ``thread`` the way that ``uid |
| 471 | search`` corresponds to ``search``. The ``thread`` command first searches the |
| 472 | mailbox for messages that match the given searching criteria using the charset |
| 473 | argument for the interpretation of strings in the searching criteria. It then |
| 474 | returns the matching messages threaded according to the specified threading |
| 475 | algorithm. |
| 476 | |
| 477 | This is an ``IMAP4rev1`` extension command. |
| 478 | |
| 479 | .. versionadded:: 2.4 |
| 480 | |
| 481 | |
| 482 | .. method:: IMAP4.uid(command, arg[, ...]) |
| 483 | |
| 484 | Execute command args with messages identified by UID, rather than message |
| 485 | number. Returns response appropriate to command. At least one argument must be |
| 486 | supplied; if none are provided, the server will return an error and an exception |
| 487 | will be raised. |
| 488 | |
| 489 | |
| 490 | .. method:: IMAP4.unsubscribe(mailbox) |
| 491 | |
| 492 | Unsubscribe from old mailbox. |
| 493 | |
| 494 | |
| 495 | .. method:: IMAP4.xatom(name[, arg[, ...]]) |
| 496 | |
| 497 | Allow simple extension commands notified by server in ``CAPABILITY`` response. |
| 498 | |
| 499 | Instances of :class:`IMAP4_SSL` have just one additional method: |
| 500 | |
| 501 | |
| 502 | .. method:: IMAP4_SSL.ssl() |
| 503 | |
| 504 | Returns SSLObject instance used for the secure connection with the server. |
| 505 | |
| 506 | The following attributes are defined on instances of :class:`IMAP4`: |
| 507 | |
| 508 | |
| 509 | .. attribute:: IMAP4.PROTOCOL_VERSION |
| 510 | |
| 511 | The most recent supported protocol in the ``CAPABILITY`` response from the |
| 512 | server. |
| 513 | |
| 514 | |
| 515 | .. attribute:: IMAP4.debug |
| 516 | |
| 517 | Integer value to control debugging output. The initialize value is taken from |
| 518 | the module variable ``Debug``. Values greater than three trace each command. |
| 519 | |
| 520 | |
| 521 | .. _imap4-example: |
| 522 | |
| 523 | IMAP4 Example |
| 524 | ------------- |
| 525 | |
| 526 | Here is a minimal example (without error checking) that opens a mailbox and |
| 527 | retrieves and prints all messages:: |
| 528 | |
| 529 | import getpass, imaplib |
| 530 | |
| 531 | M = imaplib.IMAP4() |
| 532 | M.login(getpass.getuser(), getpass.getpass()) |
| 533 | M.select() |
| 534 | typ, data = M.search(None, 'ALL') |
| 535 | for num in data[0].split(): |
| 536 | typ, data = M.fetch(num, '(RFC822)') |
| 537 | print 'Message %s\n%s\n' % (num, data[0][1]) |
| 538 | M.close() |
| 539 | M.logout() |
| 540 | |