IMAPClient is an easy-to-use, Pythonic and complete IMAP client
library.

Although IMAPClient actually uses the imaplib module from the Python
standard library under the hood, it provides a different API. Instead
of requiring that the caller performs extra parsing work, return
values are full parsed, readily usable and use sensible Python
types. Exceptions are raised when problems occur (no error checking of
return values is required).

IMAPClient is straight forward it use, but it can be useful to have at
least a general understanding of the IMAP protocol. RFC 3501
explains IMAP in detail. Other RFCs also apply to various extensions
to the base protocol. These are referred to in the documentation below
where relevant.

In the IMAP protocol, messages are identified using an integer. These
message ids are specific to a given folder.

There are two types of message identifiers in the IMAP protocol.

One type is the message sequence number where the messages in a folder
are numbered from 1 to N where N is the number of messages in the
folder. These numbers don’t persist between sessions and may be
reassigned after some operations such as an expunge.

A more convenient approach is Unique Identifiers (UIDs). Unique
Identifiers are integers assigned to each message by the IMAP server
that will persist across sessions. They do not change when folders are
expunged. Almost all IMAP servers support UIDs.

Each call to the IMAP server can use either message sequence numbers
or UIDs in the command arguments and return values. The client
specifies to the server which type of identifier should be used. You
can set whether IMAPClient should use UIDs or message sequence number
via the use_uid argument passed when an IMAPClient instance is
created and the use_uid attribute. The use_uid attribute can be
used to change the message id type between calls to the
server. IMAPClient uses UIDs by default.

Any method that accepts message ids takes either a sequence containing
message ids (eg. [1,2,3]), or a single message id integer, or a
string representing sets and ranges of messages as supported by the
IMAP protocol (e.g. '50-65', '2:*' or '2,4:7,9,12:*').

Any method that takes a folder name will accept a standard string or a
unicode string. Unicode strings will be transparently encoded using
modified UTF-7 as specified by RFC 3501#section-5.1.3. This allows
for arbitrary unicode characters (eg. non-English characters) to be
used in folder names.

The ampersand character (“&”) has special meaning in IMAP folder
names. IMAPClient automatically escapes and unescapes this character
so that the caller doesn’t have to.

Automatic folder name encoding and decoding can be enabled or disabled
with the folder_encode attribute. It defaults to True.

If folder_encode is True, all folder names returned by IMAPClient
are always returned as unicode strings. If folder_encode is False,
folder names are returned as str (Python 2) or bytes (Python 3).

IMAPClient uses sensible TLS parameter defaults for encrypted
connections and also allows for a high level of control of TLS
parameters if required. To provide a consistent API and capabilities
across Python versions the backports.ssl
library is used instead of the standard library ssl
package. backports.ssl provides an API that aims to mimic the Python
3.4 ssl package so it should be familiar to developers that have used
the ssl package in recent versions of Python.

TLS parameters are controlled by passing a backports.ssl.SSLContext
when creating an IMAPClient instance. When ssl=True is used
without passing a SSLContext, a default context is used. The default
context avoids the use of known insecure ciphers and SSL protocol
versions, with certificate verification and hostname verification
turned on. The default context will use system installed certificate
authority trust chains, if available.

IMAPClient.tls.create_default_context() returns IMAPClient’s
default context. When constructing a custom context it is usually best
to start with the default context and modify it to suit your needs.

The following example shows how to to disable certification
verification and certificate host name checks if required.

IMAPClient’s TLS functionality will not behaviour correctly if an
out-of-date version of pyOpenSSL is used. On some systems
(particularly OS X) the system installed version of pyOpenSSL will
take precedence over any user installed version. Use of virtualenvs is
strongly encouraged to work around this.

IMAPClient checks the installed pyOpenSSL version at import time and
will fail early if an old pyOpenSSL version is found.

Some extra monkey patching is required so that the gevent package can
work with pyOpenSSL (used by IMAPClient for TLS support). The
gevent_openssl package performs this patching. Please use
gevent_openssl 1.2 or later.

A connection to the IMAP server specified by host is made when
this class is instantiated.

port defaults to 143, or 993 if ssl is True.

If use_uid is True unique message UIDs be used for all calls
that accept message ids (defaults to True).

If ssl is True an SSL connection will be made (defaults to
False).

If ssl is True the optional ssl_context argument can be
used to provide a backports.ssl.SSLContext instance used to
control SSL/TLS connection parameters. If this is not provided a
sensible default context will be used.

If stream is True then host is used as the command to run
to establish a connection to the IMAP server (defaults to
False). This is useful for exotic connection or authentication
setups.

Use timeout to specify a timeout for the socket connected to the
IMAP server. The timeout applies during the initial connection to
the server and for all future socket reads and writes. The default
is for no timeout to be used.

The normalise_times attribute specifies whether datetimes
returned by fetch() are normalised to the local system time
and include no timezone information (native), or are datetimes
that include timezone information (aware). By default
normalise_times is True (times are normalised to the local
system time). This attribute can be changed between fetch()
calls if required.

The debug property can be used to enable debug logging. It can
be set to an integer from 0 to 5 where 0 disables debug output and
5 enables full output with wire logging and parsing logs. True
and False can also be assigned where True sets debug level
4.

By default, debug output goes to stderr. The log_file attribute
can be assigned to an alternate file handle for writing debug
output to.

flags should be a sequence of message flags to set. If not
specified no flags will be set.

msg_time is an optional datetime instance specifying the
date and time to set on the message. The server will set a
time if it isn’t specified. If msg_time contains timezone
information (tzinfo), this will be honoured. Otherwise the
local machine’s time zone sent to the server.

If the session is authenticated and the server has returned an
untagged CAPABILITY response at authentication time, this
response will be returned. Otherwise, the CAPABILITY command
will be issued to the server, with the results cached for
future calls.

If the session is not yet authenticated, the capabilities
requested at connection time will be returned.

Retrieve selected data associated with one or more
messages in the currently selected folder.

data should be specified as a sequnce of strings, one item
per data selector, for example ['INTERNALDATE','RFC822'].

modifiers are required for some extensions to the IMAP
protocol (eg. RFC 4551). These should be a sequnce of strings
if specified, for example ['CHANGEDSINCE123'].

A dictionary is returned, indexed by message number. Each item
in this dictionary is also a dictionary, with an entry
corresponding to each item in data. Returned values will be
appropriately typed. For example, integer values will be returned as
Python integers, timestamps will be returned as datetime
instances and ENVELOPE responses will be returned as
Envelope instances.

String data will generally be returned as bytes (Python 3) or
str (Python 2).

In addition to an element for each data item, the dict
returned for each message also contains a SEQ key containing
the sequence number for the message. This allows for mapping
between the UID and sequence number (when the use_uid
property is True).

In this mode the server will return unsolicited responses
about changes to the selected mailbox. This method returns
immediately. Use idle_check() to look for IDLE responses
and idle_done() to stop IDLE mode.

Note

Any other commmands issued while the server is in IDLE
mode will fail.

This method should only be called if the server is already in
IDLE mode.

The return value is of the form (command_text,idle_responses) where command_text is the text sent by the
server when the IDLE command finished (eg. b'Idleterminated') and idle_responses is a list of parsed idle
responses received since the last call to idle_check() (if
any). These are returned in parsed form as per
idle_check().

Get a listing of folders on the server as a list of
(flags,delimiter,name) tuples.

Specifying directory will limit returned folders to the
given base directory. The directory and any child directories
will returned.

Specifying pattern will limit returned folders to those with
matching names. The wildcards are supported in
pattern. * matches zero or more of any character and
% matches 0 or more characters except the folder
delimiter.

Calling list_folders with no arguments will recursively list
all folders available for the logged in user.

Folder names are always returned as unicode strings, and
decoded from modified UTF-7, except if folder_decode is not
set.

IMAPClient will perform conversion and quoting as
required. The caller shouldn’t do this.

It is also possible (but not recommended) to pass the combined
criteria as a single string. In this case IMAPClient won’t
perform quoting, allowing lower-level specification of
criteria. Examples of this style:

The ssl_context argument is optional and should be a
backports.ssl.SSLContext object. If no SSL context
is given, a SSL context with reasonable default settings will be used.

You can enable checking of the hostname in the certificate presented
by the server against the hostname which was used for connecting, by
setting the check_hostname attribute of the SSL context to True.
The default SSL context has this setting enabled.

Raises Error if the SSL connection could not be established.

Raises AbortError if the server does not support STARTTLS
or an SSL connection is already established.

This method returns special flags for each folder and a
localized name for certain folders (e.g. the name of the
inbox may be localized and the flags can be used to
determine the actual inbox, even if the name has been
localized.

The first Address, where host is None, indicates the start
of the group. The mailbox field contains the group name. The
final Address, where both mailbox and host are None,
indicates the end of the group.

When developing program using IMAPClient is it sometimes useful to
have an interactive shell to play with. IMAPClient ships with a module
that lets you fire up an interactive shell with an IMAPClient instance
connected to an IMAP server.

Start a session like this:

python -m imapclient.interact -H <host> -u <user> ...

Various options are available to specify the IMAP server details. See
the help (–help) for more details. You’ll be prompted for a username
and password if one isn’t provided on the command line.

It is also possible to pass connection details as a configuration file
like this: