| 1 |
:mod:`!imaplib` --- IMAP4 protocol client |
| 2 |
========================================= |
| 3 |
|
| 4 |
.. module:: imaplib |
| 5 |
:synopsis: IMAP4 protocol client (requires sockets). |
| 6 |
|
| 7 |
.. moduleauthor:: Piers Lauder <[email protected]> |
| 8 |
.. sectionauthor:: Piers Lauder <[email protected]> |
| 9 |
.. revised by ESR, January 2000 |
| 10 |
.. changes for IMAP4_SSL by Tino Lange <[email protected]>, March 2002 |
| 11 |
.. changes for IMAP4_stream by Piers Lauder <[email protected]>, |
| 12 |
November 2002 |
| 13 |
.. changes for IMAP4 IDLE by Forest <[email protected]>, August 2024 |
| 14 |
|
| 15 |
**Source code:** :source:`Lib/imaplib.py` |
| 16 |
|
| 17 |
.. index:: |
| 18 |
pair: IMAP4; protocol |
| 19 |
pair: IMAP4_SSL; protocol |
| 20 |
pair: IMAP4_stream; protocol |
| 21 |
|
| 22 |
-------------- |
| 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 |
.. include:: ../includes/wasm-notavail.rst |
| 31 |
|
| 32 |
Three classes are provided by the :mod:`!imaplib` module, :class:`IMAP4` is the |
| 33 |
base class: |
| 34 |
|
| 35 |
|
| 36 |
.. class:: IMAP4(host='', port=IMAP4_PORT, timeout=None) |
| 37 |
|
| 38 |
This class implements the actual IMAP4 protocol. The connection is created and |
| 39 |
protocol version (IMAP4 or IMAP4rev1) is determined when the instance is |
| 40 |
initialized. If *host* is not specified, ``''`` (the local host) is used. If |
| 41 |
*port* is omitted, the standard IMAP4 port (143) is used. The optional *timeout* |
| 42 |
parameter specifies a timeout in seconds for the connection attempt. |
| 43 |
If timeout is not given or is ``None``, the global default socket timeout is used. |
| 44 |
|
| 45 |
The :class:`IMAP4` class supports the :keyword:`with` statement. When used |
| 46 |
like this, the IMAP4 ``LOGOUT`` command is issued automatically when the |
| 47 |
:keyword:`!with` statement exits. E.g.:: |
| 48 |
|
| 49 |
>>> from imaplib import IMAP4 |
| 50 |
>>> with IMAP4("domain.org") as M: |
| 51 |
... M.noop() |
| 52 |
... |
| 53 |
('OK', [b'Nothing Accomplished. d25if65hy903weo.87']) |
| 54 |
|
| 55 |
.. versionchanged:: 3.5 |
| 56 |
Support for the :keyword:`with` statement was added. |
| 57 |
|
| 58 |
.. versionchanged:: 3.9 |
| 59 |
The optional *timeout* parameter was added. |
| 60 |
|
| 61 |
Three exceptions are defined as attributes of the :class:`IMAP4` class: |
| 62 |
|
| 63 |
|
| 64 |
.. exception:: IMAP4.error |
| 65 |
|
| 66 |
Exception raised on any errors. The reason for the exception is passed to the |
| 67 |
constructor as a string. |
| 68 |
|
| 69 |
|
| 70 |
.. exception:: IMAP4.abort |
| 71 |
|
| 72 |
IMAP4 server errors cause this exception to be raised. This is a sub-class of |
| 73 |
:exc:`IMAP4.error`. Note that closing the instance and instantiating a new one |
| 74 |
will usually allow recovery from this exception. |
| 75 |
|
| 76 |
|
| 77 |
.. exception:: IMAP4.readonly |
| 78 |
|
| 79 |
This exception is raised when a writable mailbox has its status changed by the |
| 80 |
server. This is a sub-class of :exc:`IMAP4.error`. Some other client now has |
| 81 |
write permission, and the mailbox will need to be re-opened to re-obtain write |
| 82 |
permission. |
| 83 |
|
| 84 |
|
| 85 |
There's also a subclass for secure connections: |
| 86 |
|
| 87 |
|
| 88 |
.. class:: IMAP4_SSL(host='', port=IMAP4_SSL_PORT, *, ssl_context=None, \ |
| 89 |
timeout=None) |
| 90 |
|
| 91 |
This is a subclass derived from :class:`IMAP4` that connects over an SSL |
| 92 |
encrypted socket (to use this class you need a socket module that was compiled |
| 93 |
with SSL support). If *host* is not specified, ``''`` (the local host) is used. |
| 94 |
If *port* is omitted, the standard IMAP4-over-SSL port (993) is used. |
| 95 |
*ssl_context* is a :class:`ssl.SSLContext` object which allows bundling |
| 96 |
SSL configuration options, certificates and private keys into a single |
| 97 |
(potentially long-lived) structure. Please read :ref:`ssl-security` for |
| 98 |
best practices. |
| 99 |
|
| 100 |
The optional *timeout* parameter specifies a timeout in seconds for the |
| 101 |
connection attempt. If timeout is not given or is ``None``, the global default |
| 102 |
socket timeout is used. |
| 103 |
|
| 104 |
.. versionchanged:: 3.3 |
| 105 |
*ssl_context* parameter was added. |
| 106 |
|
| 107 |
.. versionchanged:: 3.4 |
| 108 |
The class now supports hostname check with |
| 109 |
:attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see |
| 110 |
:const:`ssl.HAS_SNI`). |
| 111 |
|
| 112 |
.. versionchanged:: 3.9 |
| 113 |
The optional *timeout* parameter was added. |
| 114 |
|
| 115 |
.. versionchanged:: 3.12 |
| 116 |
The deprecated *keyfile* and *certfile* parameters have been removed. |
| 117 |
|
| 118 |
The second subclass allows for connections created by a child process: |
| 119 |
|
| 120 |
|
| 121 |
.. class:: IMAP4_stream(command) |
| 122 |
|
| 123 |
This is a subclass derived from :class:`IMAP4` that connects to the |
| 124 |
``stdin/stdout`` file descriptors created by passing *command* to |
| 125 |
``subprocess.Popen()``. |
| 126 |
|
| 127 |
|
| 128 |
The following utility functions are defined: |
| 129 |
|
| 130 |
|
| 131 |
.. function:: Internaldate2tuple(datestr) |
| 132 |
|
| 133 |
Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local |
| 134 |
time. The return value is a :class:`time.struct_time` tuple or |
| 135 |
``None`` if the string has wrong format. |
| 136 |
|
| 137 |
.. function:: Int2AP(num) |
| 138 |
|
| 139 |
Converts an integer into a bytes representation using characters from the set |
| 140 |
[``A`` .. ``P``]. |
| 141 |
|
| 142 |
|
| 143 |
.. function:: ParseFlags(flagstr) |
| 144 |
|
| 145 |
Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags. |
| 146 |
|
| 147 |
|
| 148 |
.. function:: Time2Internaldate(date_time) |
| 149 |
|
| 150 |
Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation. |
| 151 |
The return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS |
| 152 |
+HHMM"`` (including double-quotes). The *date_time* argument can |
| 153 |
be a number (int or float) representing seconds since epoch (as |
| 154 |
returned by :func:`time.time`), a 9-tuple representing local time |
| 155 |
an instance of :class:`time.struct_time` (as returned by |
| 156 |
:func:`time.localtime`), an aware instance of |
| 157 |
:class:`datetime.datetime`, or a double-quoted string. In the last |
| 158 |
case, it is assumed to already be in the correct format. |
| 159 |
|
| 160 |
Note that IMAP4 message numbers change as the mailbox changes; in particular, |
| 161 |
after an ``EXPUNGE`` command performs deletions the remaining messages are |
| 162 |
renumbered. So it is highly advisable to use UIDs instead, with the UID command. |
| 163 |
|
| 164 |
At the end of the module, there is a test section that contains a more extensive |
| 165 |
example of usage. |
| 166 |
|
| 167 |
|
| 168 |
.. seealso:: |
| 169 |
|
| 170 |
Documents describing the protocol, sources for servers |
| 171 |
implementing it, by the University of Washington's IMAP Information Center |
| 172 |
can all be found at (**Source Code**) https://github.com/uw-imap/imap (**Not Maintained**). |
| 173 |
|
| 174 |
|
| 175 |
.. _imap4-objects: |
| 176 |
|
| 177 |
IMAP4 Objects |
| 178 |
------------- |
| 179 |
|
| 180 |
All IMAP4rev1 commands are represented by methods of the same name, either |
| 181 |
uppercase or lowercase. |
| 182 |
|
| 183 |
All arguments to commands are converted to strings, except for ``AUTHENTICATE``, |
| 184 |
and the last argument to ``APPEND`` which is passed as an IMAP4 literal. If |
| 185 |
necessary (the string contains IMAP4 protocol-sensitive characters and isn't |
| 186 |
enclosed with either parentheses or double quotes) each string is quoted. |
| 187 |
However, the *password* argument to the ``LOGIN`` command is always quoted. If |
| 188 |
you want to avoid having an argument string quoted (eg: the *flags* argument to |
| 189 |
``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``). |
| 190 |
|
| 191 |
Most commands return a tuple: ``(type, [data, ...])`` where *type* is usually |
| 192 |
``'OK'`` or ``'NO'``, and *data* is either the text from the command response, |
| 193 |
or mandated results from the command. Each *data* is either a ``bytes``, or a |
| 194 |
tuple. If a tuple, then the first part is the header of the response, and the |
| 195 |
second part contains the data (ie: 'literal' value). |
| 196 |
|
| 197 |
The *message_set* options to commands below is a string specifying one or more |
| 198 |
messages to be acted upon. It may be a simple message number (``'1'``), a range |
| 199 |
of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by |
| 200 |
commas (``'1:3,6:9'``). A range can contain an asterisk to indicate an infinite |
| 201 |
upper bound (``'3:*'``). |
| 202 |
|
| 203 |
An :class:`IMAP4` instance has the following methods: |
| 204 |
|
| 205 |
|
| 206 |
.. method:: IMAP4.append(mailbox, flags, date_time, message) |
| 207 |
|
| 208 |
Append *message* to named mailbox. |
| 209 |
|
| 210 |
|
| 211 |
.. method:: IMAP4.authenticate(mechanism, authobject) |
| 212 |
|
| 213 |
Authenticate command --- requires response processing. |
| 214 |
|
| 215 |
*mechanism* specifies which authentication mechanism is to be used - it should |
| 216 |
appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``. |
| 217 |
|
| 218 |
*authobject* must be a callable object:: |
| 219 |
|
| 220 |
data = authobject(response) |
| 221 |
|
| 222 |
It will be called to process server continuation responses; the *response* |
| 223 |
argument it is passed will be ``bytes``. It should return ``bytes`` *data* |
| 224 |
that will be base64 encoded and sent to the server. It should return |
| 225 |
``None`` if the client abort response ``*`` should be sent instead. |
| 226 |
|
| 227 |
.. versionchanged:: 3.5 |
| 228 |
string usernames and passwords are now encoded to ``utf-8`` instead of |
| 229 |
being limited to ASCII. |
| 230 |
|
| 231 |
|
| 232 |
.. method:: IMAP4.check() |
| 233 |
|
| 234 |
Checkpoint mailbox on server. |
| 235 |
|
| 236 |
|
| 237 |
.. method:: IMAP4.close() |
| 238 |
|
| 239 |
Close currently selected mailbox. Deleted messages are removed from writable |
| 240 |
mailbox. This is the recommended command before ``LOGOUT``. |
| 241 |
|
| 242 |
|
| 243 |
.. method:: IMAP4.copy(message_set, new_mailbox) |
| 244 |
|
| 245 |
Copy *message_set* messages onto end of *new_mailbox*. |
| 246 |
|
| 247 |
|
| 248 |
.. method:: IMAP4.create(mailbox) |
| 249 |
|
| 250 |
Create new mailbox named *mailbox*. |
| 251 |
|
| 252 |
|
| 253 |
.. method:: IMAP4.delete(mailbox) |
| 254 |
|
| 255 |
Delete old mailbox named *mailbox*. |
| 256 |
|
| 257 |
|
| 258 |
.. method:: IMAP4.deleteacl(mailbox, who) |
| 259 |
|
| 260 |
Delete the ACLs (remove any rights) set for who on mailbox. |
| 261 |
|
| 262 |
|
| 263 |
.. method:: IMAP4.enable(capability) |
| 264 |
|
| 265 |
Enable *capability* (see :rfc:`5161`). Most capabilities do not need to be |
| 266 |
enabled. Currently only the ``UTF8=ACCEPT`` capability is supported |
| 267 |
(see :RFC:`6855`). |
| 268 |
|
| 269 |
.. versionadded:: 3.5 |
| 270 |
The :meth:`enable` method itself, and :RFC:`6855` support. |
| 271 |
|
| 272 |
|
| 273 |
.. method:: IMAP4.expunge() |
| 274 |
|
| 275 |
Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE`` |
| 276 |
response for each deleted message. Returned data contains a list of ``EXPUNGE`` |
| 277 |
message numbers in order received. |
| 278 |
|
| 279 |
|
| 280 |
.. method:: IMAP4.fetch(message_set, message_parts) |
| 281 |
|
| 282 |
Fetch (parts of) messages. *message_parts* should be a string of message part |
| 283 |
names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``. Returned data |
| 284 |
are tuples of message part envelope and data. |
| 285 |
|
| 286 |
|
| 287 |
.. method:: IMAP4.getacl(mailbox) |
| 288 |
|
| 289 |
Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported |
| 290 |
by the ``Cyrus`` server. |
| 291 |
|
| 292 |
|
| 293 |
.. method:: IMAP4.getannotation(mailbox, entry, attribute) |
| 294 |
|
| 295 |
Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is |
| 296 |
non-standard, but is supported by the ``Cyrus`` server. |
| 297 |
|
| 298 |
|
| 299 |
.. method:: IMAP4.getquota(root) |
| 300 |
|
| 301 |
Get the ``quota`` *root*'s resource usage and limits. This method is part of the |
| 302 |
IMAP4 QUOTA extension defined in rfc2087. |
| 303 |
|
| 304 |
|
| 305 |
.. method:: IMAP4.getquotaroot(mailbox) |
| 306 |
|
| 307 |
Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part |
| 308 |
of the IMAP4 QUOTA extension defined in rfc2087. |
| 309 |
|
| 310 |
|
| 311 |
.. method:: IMAP4.idle(duration=None) |
| 312 |
|
| 313 |
Return an :class:`!Idler`: an iterable context manager implementing the |
| 314 |
IMAP4 ``IDLE`` command as defined in :rfc:`2177`. |
| 315 |
|
| 316 |
The returned object sends the ``IDLE`` command when activated by the |
| 317 |
:keyword:`with` statement, produces IMAP untagged responses via the |
| 318 |
:term:`iterator` protocol, and sends ``DONE`` upon context exit. |
| 319 |
|
| 320 |
All untagged responses that arrive after sending the ``IDLE`` command |
| 321 |
(including any that arrive before the server acknowledges the command) will |
| 322 |
be available via iteration. Any leftover responses (those not iterated in |
| 323 |
the :keyword:`with` context) can be retrieved in the usual way after |
| 324 |
``IDLE`` ends, using :meth:`IMAP4.response`. |
| 325 |
|
| 326 |
Responses are represented as ``(type, [data, ...])`` tuples, as described |
| 327 |
in :ref:`IMAP4 Objects <imap4-objects>`. |
| 328 |
|
| 329 |
The *duration* argument sets a maximum duration (in seconds) to keep idling, |
| 330 |
after which any ongoing iteration will stop. It can be an :class:`int` or |
| 331 |
:class:`float`, or ``None`` for no time limit. |
| 332 |
Callers wishing to avoid inactivity timeouts on servers that impose them |
| 333 |
should keep this at most 29 minutes (1740 seconds). |
| 334 |
Requires a socket connection; *duration* must be ``None`` on |
| 335 |
:class:`IMAP4_stream` connections. |
| 336 |
|
| 337 |
.. code-block:: pycon |
| 338 |
|
| 339 |
>>> with M.idle(duration=29 * 60) as idler: |
| 340 |
... for typ, data in idler: |
| 341 |
... print(typ, data) |
| 342 |
... |
| 343 |
EXISTS [b'1'] |
| 344 |
RECENT [b'1'] |
| 345 |
|
| 346 |
|
| 347 |
.. method:: Idler.burst(interval=0.1) |
| 348 |
|
| 349 |
Yield a burst of responses no more than *interval* seconds apart |
| 350 |
(expressed as an :class:`int` or :class:`float`). |
| 351 |
|
| 352 |
This :term:`generator` is an alternative to iterating one response at a |
| 353 |
time, intended to aid in efficient batch processing. It retrieves the |
| 354 |
next response along with any immediately available subsequent responses. |
| 355 |
(For example, a rapid series of ``EXPUNGE`` responses after a bulk |
| 356 |
delete.) |
| 357 |
|
| 358 |
Requires a socket connection; does not work on :class:`IMAP4_stream` |
| 359 |
connections. |
| 360 |
|
| 361 |
.. code-block:: pycon |
| 362 |
|
| 363 |
>>> with M.idle() as idler: |
| 364 |
... # get a response and any others following by < 0.1 seconds |
| 365 |
... batch = list(idler.burst()) |
| 366 |
... print(f'processing {len(batch)} responses...') |
| 367 |
... print(batch) |
| 368 |
... |
| 369 |
processing 3 responses... |
| 370 |
[('EXPUNGE', [b'2']), ('EXPUNGE', [b'1']), ('RECENT', [b'0'])] |
| 371 |
|
| 372 |
.. tip:: |
| 373 |
|
| 374 |
The ``IDLE`` context's maximum duration, as passed to |
| 375 |
:meth:`IMAP4.idle`, is respected when waiting for the first response |
| 376 |
in a burst. Therefore, an expired :class:`!Idler` will cause this |
| 377 |
generator to return immediately without producing anything. Callers |
| 378 |
should consider this if using it in a loop. |
| 379 |
|
| 380 |
|
| 381 |
.. note:: |
| 382 |
|
| 383 |
The iterator returned by :meth:`IMAP4.idle` is usable only within a |
| 384 |
:keyword:`with` statement. Before or after that context, unsolicited |
| 385 |
responses are collected internally whenever a command finishes, and can |
| 386 |
be retrieved with :meth:`IMAP4.response`. |
| 387 |
|
| 388 |
.. note:: |
| 389 |
|
| 390 |
The :class:`!Idler` class name and structure are internal interfaces, |
| 391 |
subject to change. Calling code can rely on its context management, |
| 392 |
iteration, and public method to remain stable, but should not subclass, |
| 393 |
instantiate, compare, or otherwise directly reference the class. |
| 394 |
|
| 395 |
.. versionadded:: 3.14 |
| 396 |
|
| 397 |
|
| 398 |
.. method:: IMAP4.list([directory[, pattern]]) |
| 399 |
|
| 400 |
List mailbox names in *directory* matching *pattern*. *directory* defaults to |
| 401 |
the top-level mail folder, and *pattern* defaults to match anything. Returned |
| 402 |
data contains a list of ``LIST`` responses. |
| 403 |
|
| 404 |
|
| 405 |
.. method:: IMAP4.login(user, password) |
| 406 |
|
| 407 |
Identify the client using a plaintext password. The *password* will be quoted. |
| 408 |
|
| 409 |
|
| 410 |
.. method:: IMAP4.login_cram_md5(user, password) |
| 411 |
|
| 412 |
Force use of ``CRAM-MD5`` authentication when identifying the client to protect |
| 413 |
the password. Will only work if the server ``CAPABILITY`` response includes the |
| 414 |
phrase ``AUTH=CRAM-MD5``. |
| 415 |
|
| 416 |
.. versionchanged:: 3.14 |
| 417 |
An :exc:`IMAP4.error` is raised if MD5 support is not available. |
| 418 |
|
| 419 |
|
| 420 |
.. method:: IMAP4.logout() |
| 421 |
|
| 422 |
Shutdown connection to server. Returns server ``BYE`` response. |
| 423 |
|
| 424 |
.. versionchanged:: 3.8 |
| 425 |
The method no longer ignores silently arbitrary exceptions. |
| 426 |
|
| 427 |
|
| 428 |
.. method:: IMAP4.lsub(directory='""', pattern='*') |
| 429 |
|
| 430 |
List subscribed mailbox names in directory matching pattern. *directory* |
| 431 |
defaults to the top level directory and *pattern* defaults to match any mailbox. |
| 432 |
Returned data are tuples of message part envelope and data. |
| 433 |
|
| 434 |
|
| 435 |
.. method:: IMAP4.myrights(mailbox) |
| 436 |
|
| 437 |
Show my ACLs for a mailbox (i.e. the rights that I have on mailbox). |
| 438 |
|
| 439 |
|
| 440 |
.. method:: IMAP4.namespace() |
| 441 |
|
| 442 |
Returns IMAP namespaces as defined in :rfc:`2342`. |
| 443 |
|
| 444 |
|
| 445 |
.. method:: IMAP4.noop() |
| 446 |
|
| 447 |
Send ``NOOP`` to server. |
| 448 |
|
| 449 |
|
| 450 |
.. method:: IMAP4.open(host, port, timeout=None) |
| 451 |
|
| 452 |
Opens socket to *port* at *host*. The optional *timeout* parameter |
| 453 |
specifies a timeout in seconds for the connection attempt. |
| 454 |
If timeout is not given or is ``None``, the global default socket timeout |
| 455 |
is used. Also note that if the *timeout* parameter is set to be zero, |
| 456 |
it will raise a :class:`ValueError` to reject creating a non-blocking socket. |
| 457 |
This method is implicitly called by the :class:`IMAP4` constructor. |
| 458 |
The connection objects established by this method will be used in |
| 459 |
the :meth:`IMAP4.read`, :meth:`IMAP4.readline`, :meth:`IMAP4.send`, |
| 460 |
and :meth:`IMAP4.shutdown` methods. You may override this method. |
| 461 |
|
| 462 |
.. audit-event:: imaplib.open self,host,port imaplib.IMAP4.open |
| 463 |
|
| 464 |
.. versionchanged:: 3.9 |
| 465 |
The *timeout* parameter was added. |
| 466 |
|
| 467 |
.. method:: IMAP4.partial(message_num, message_part, start, length) |
| 468 |
|
| 469 |
Fetch truncated part of a message. Returned data is a tuple of message part |
| 470 |
envelope and data. |
| 471 |
|
| 472 |
|
| 473 |
.. method:: IMAP4.proxyauth(user) |
| 474 |
|
| 475 |
Assume authentication as *user*. Allows an authorised administrator to proxy |
| 476 |
into any user's mailbox. |
| 477 |
|
| 478 |
|
| 479 |
.. method:: IMAP4.read(size) |
| 480 |
|
| 481 |
Reads *size* bytes from the remote server. You may override this method. |
| 482 |
|
| 483 |
|
| 484 |
.. method:: IMAP4.readline() |
| 485 |
|
| 486 |
Reads one line from the remote server. You may override this method. |
| 487 |
|
| 488 |
|
| 489 |
.. method:: IMAP4.recent() |
| 490 |
|
| 491 |
Prompt server for an update. Returned data is ``None`` if no new messages, else |
| 492 |
value of ``RECENT`` response. |
| 493 |
|
| 494 |
|
| 495 |
.. method:: IMAP4.rename(oldmailbox, newmailbox) |
| 496 |
|
| 497 |
Rename mailbox named *oldmailbox* to *newmailbox*. |
| 498 |
|
| 499 |
|
| 500 |
.. method:: IMAP4.response(code) |
| 501 |
|
| 502 |
Return data for response *code* if received, or ``None``. Returns the given |
| 503 |
code, instead of the usual type. |
| 504 |
|
| 505 |
|
| 506 |
.. method:: IMAP4.search(charset, criterion[, ...]) |
| 507 |
|
| 508 |
Search mailbox for matching messages. *charset* may be ``None``, in which case |
| 509 |
no ``CHARSET`` will be specified in the request to the server. The IMAP |
| 510 |
protocol requires that at least one criterion be specified; an exception will be |
| 511 |
raised when the server returns an error. *charset* must be ``None`` if |
| 512 |
the ``UTF8=ACCEPT`` capability was enabled using the :meth:`enable` |
| 513 |
command. |
| 514 |
|
| 515 |
Example:: |
| 516 |
|
| 517 |
# M is a connected IMAP4 instance... |
| 518 |
typ, msgnums = M.search(None, 'FROM', '"LDJ"') |
| 519 |
|
| 520 |
# or: |
| 521 |
typ, msgnums = M.search(None, '(FROM "LDJ")') |
| 522 |
|
| 523 |
|
| 524 |
.. method:: IMAP4.select(mailbox='INBOX', readonly=False) |
| 525 |
|
| 526 |
Select a mailbox. Returned data is the count of messages in *mailbox* |
| 527 |
(``EXISTS`` response). The default *mailbox* is ``'INBOX'``. If the *readonly* |
| 528 |
flag is set, modifications to the mailbox are not allowed. |
| 529 |
|
| 530 |
|
| 531 |
.. method:: IMAP4.send(data) |
| 532 |
|
| 533 |
Sends ``data`` to the remote server. You may override this method. |
| 534 |
|
| 535 |
.. audit-event:: imaplib.send self,data imaplib.IMAP4.send |
| 536 |
|
| 537 |
|
| 538 |
.. method:: IMAP4.setacl(mailbox, who, what) |
| 539 |
|
| 540 |
Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by |
| 541 |
the ``Cyrus`` server. |
| 542 |
|
| 543 |
|
| 544 |
.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...]) |
| 545 |
|
| 546 |
Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is |
| 547 |
supported by the ``Cyrus`` server. |
| 548 |
|
| 549 |
|
| 550 |
.. method:: IMAP4.setquota(root, limits) |
| 551 |
|
| 552 |
Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4 |
| 553 |
QUOTA extension defined in rfc2087. |
| 554 |
|
| 555 |
|
| 556 |
.. method:: IMAP4.shutdown() |
| 557 |
|
| 558 |
Close connection established in ``open``. This method is implicitly |
| 559 |
called by :meth:`IMAP4.logout`. You may override this method. |
| 560 |
|
| 561 |
|
| 562 |
.. method:: IMAP4.socket() |
| 563 |
|
| 564 |
Returns socket instance used to connect to server. |
| 565 |
|
| 566 |
|
| 567 |
.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...]) |
| 568 |
|
| 569 |
The ``sort`` command is a variant of ``search`` with sorting semantics for the |
| 570 |
results. Returned data contains a space separated list of matching message |
| 571 |
numbers. |
| 572 |
|
| 573 |
Sort has two arguments before the *search_criterion* argument(s); a |
| 574 |
parenthesized list of *sort_criteria*, and the searching *charset*. Note that |
| 575 |
unlike ``search``, the searching *charset* argument is mandatory. There is also |
| 576 |
a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search`` |
| 577 |
corresponds to ``search``. The ``sort`` command first searches the mailbox for |
| 578 |
messages that match the given searching criteria using the charset argument for |
| 579 |
the interpretation of strings in the searching criteria. It then returns the |
| 580 |
numbers of matching messages. |
| 581 |
|
| 582 |
This is an ``IMAP4rev1`` extension command. |
| 583 |
|
| 584 |
|
| 585 |
.. method:: IMAP4.starttls(ssl_context=None) |
| 586 |
|
| 587 |
Send a ``STARTTLS`` command. The *ssl_context* argument is optional |
| 588 |
and should be a :class:`ssl.SSLContext` object. This will enable |
| 589 |
encryption on the IMAP connection. Please read :ref:`ssl-security` for |
| 590 |
best practices. |
| 591 |
|
| 592 |
.. versionadded:: 3.2 |
| 593 |
|
| 594 |
.. versionchanged:: 3.4 |
| 595 |
The method now supports hostname check with |
| 596 |
:attr:`ssl.SSLContext.check_hostname` and *Server Name Indication* (see |
| 597 |
:const:`ssl.HAS_SNI`). |
| 598 |
|
| 599 |
|
| 600 |
.. method:: IMAP4.status(mailbox, names) |
| 601 |
|
| 602 |
Request named status conditions for *mailbox*. |
| 603 |
|
| 604 |
|
| 605 |
.. method:: IMAP4.store(message_set, command, flag_list) |
| 606 |
|
| 607 |
Alters flag dispositions for messages in mailbox. *command* is specified by |
| 608 |
section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS", |
| 609 |
optionally with a suffix of ".SILENT". |
| 610 |
|
| 611 |
For example, to set the delete flag on all messages:: |
| 612 |
|
| 613 |
typ, data = M.search(None, 'ALL') |
| 614 |
for num in data[0].split(): |
| 615 |
M.store(num, '+FLAGS', '\\Deleted') |
| 616 |
M.expunge() |
| 617 |
|
| 618 |
.. note:: |
| 619 |
|
| 620 |
Creating flags containing ']' (for example: "[test]") violates |
| 621 |
:rfc:`3501` (the IMAP protocol). However, imaplib has historically |
| 622 |
allowed creation of such tags, and popular IMAP servers, such as Gmail, |
| 623 |
accept and produce such flags. There are non-Python programs which also |
| 624 |
create such tags. Although it is an RFC violation and IMAP clients and |
| 625 |
servers are supposed to be strict, imaplib still continues to allow |
| 626 |
such tags to be created for backward compatibility reasons, and as of |
| 627 |
Python 3.6, handles them if they are sent from the server, since this |
| 628 |
improves real-world compatibility. |
| 629 |
|
| 630 |
.. method:: IMAP4.subscribe(mailbox) |
| 631 |
|
| 632 |
Subscribe to new mailbox. |
| 633 |
|
| 634 |
|
| 635 |
.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...]) |
| 636 |
|
| 637 |
The ``thread`` command is a variant of ``search`` with threading semantics for |
| 638 |
the results. Returned data contains a space separated list of thread members. |
| 639 |
|
| 640 |
Thread members consist of zero or more messages numbers, delimited by spaces, |
| 641 |
indicating successive parent and child. |
| 642 |
|
| 643 |
Thread has two arguments before the *search_criterion* argument(s); a |
| 644 |
*threading_algorithm*, and the searching *charset*. Note that unlike |
| 645 |
``search``, the searching *charset* argument is mandatory. There is also a |
| 646 |
``uid thread`` command which corresponds to ``thread`` the way that ``uid |
| 647 |
search`` corresponds to ``search``. The ``thread`` command first searches the |
| 648 |
mailbox for messages that match the given searching criteria using the *charset* |
| 649 |
argument for the interpretation of strings in the searching criteria. It then |
| 650 |
returns the matching messages threaded according to the specified threading |
| 651 |
algorithm. |
| 652 |
|
| 653 |
This is an ``IMAP4rev1`` extension command. |
| 654 |
|
| 655 |
|
| 656 |
.. method:: IMAP4.uid(command, arg[, ...]) |
| 657 |
|
| 658 |
Execute command args with messages identified by UID, rather than message |
| 659 |
number. Returns response appropriate to command. At least one argument must be |
| 660 |
supplied; if none are provided, the server will return an error and an exception |
| 661 |
will be raised. |
| 662 |
|
| 663 |
|
| 664 |
.. method:: IMAP4.unsubscribe(mailbox) |
| 665 |
|
| 666 |
Unsubscribe from old mailbox. |
| 667 |
|
| 668 |
.. method:: IMAP4.unselect() |
| 669 |
|
| 670 |
:meth:`imaplib.IMAP4.unselect` frees server's resources associated with the |
| 671 |
selected mailbox and returns the server to the authenticated |
| 672 |
state. This command performs the same actions as :meth:`imaplib.IMAP4.close`, except |
| 673 |
that no messages are permanently removed from the currently |
| 674 |
selected mailbox. |
| 675 |
|
| 676 |
.. versionadded:: 3.9 |
| 677 |
|
| 678 |
.. method:: IMAP4.xatom(name[, ...]) |
| 679 |
|
| 680 |
Allow simple extension commands notified by server in ``CAPABILITY`` response. |
| 681 |
|
| 682 |
|
| 683 |
The following attributes are defined on instances of :class:`IMAP4`: |
| 684 |
|
| 685 |
.. attribute:: IMAP4.PROTOCOL_VERSION |
| 686 |
|
| 687 |
The most recent supported protocol in the ``CAPABILITY`` response from the |
| 688 |
server. |
| 689 |
|
| 690 |
|
| 691 |
.. attribute:: IMAP4.debug |
| 692 |
|
| 693 |
Integer value to control debugging output. The initialize value is taken from |
| 694 |
the module variable ``Debug``. Values greater than three trace each command. |
| 695 |
|
| 696 |
|
| 697 |
.. attribute:: IMAP4.utf8_enabled |
| 698 |
|
| 699 |
Boolean value that is normally ``False``, but is set to ``True`` if an |
| 700 |
:meth:`enable` command is successfully issued for the ``UTF8=ACCEPT`` |
| 701 |
capability. |
| 702 |
|
| 703 |
.. versionadded:: 3.5 |
| 704 |
|
| 705 |
|
| 706 |
.. _imap4-example: |
| 707 |
|
| 708 |
IMAP4 Example |
| 709 |
------------- |
| 710 |
|
| 711 |
Here is a minimal example (without error checking) that opens a mailbox and |
| 712 |
retrieves and prints all messages:: |
| 713 |
|
| 714 |
import getpass, imaplib |
| 715 |
|
| 716 |
M = imaplib.IMAP4(host='example.org') |
| 717 |
M.login(getpass.getuser(), getpass.getpass()) |
| 718 |
M.select() |
| 719 |
typ, data = M.search(None, 'ALL') |
| 720 |
for num in data[0].split(): |
| 721 |
typ, data = M.fetch(num, '(RFC822)') |
| 722 |
print('Message %s\n%s\n' % (num, data[0][1])) |
| 723 |
M.close() |
| 724 |
M.logout() |
| 725 |
|