IMAPClient Class

The primary class used by the imapclient package is the IMAPClient class. All interaction with a remote IMAP server is performed via an IMAPClient instance.

class imapclient.IMAPClient(host, port=None, use_uid=True, ssl=True, stream=False, ssl_context=None, timeout=None)[source]

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

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

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

If ssl is True (the default) a secure connection will be made. Otherwise an insecure connection over plain text will be established.

If ssl is True the optional ssl_context argument can be used to provide an 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 can be either a float number, or an instance of imapclient.SocketTimeout.

  • If a single float number is passed, the same timeout delay applies during the initial connection to the server and for all future socket reads and writes.
  • In case of a SocketTimeout, connection timeout and read/write operations can have distinct timeouts.
  • The default is None, where no timeout is 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.

Can be used as a context manager to automatically close opened connections:

>>> with IMAPClient(host="") as client:
...     client.login("", "passwd")

alias of imaplib.IMAP4.abort


alias of imaplib.IMAP4.error


alias of imaplib.IMAP4.readonly

add_flags(messages, flags, silent=False)[source]

Add flags to messages in the currently selected folder.

flags should be a sequence of strings.

Returns the flags set for each modified message (see get_flags), or None if silent is true.

add_gmail_labels(messages, labels, silent=False)[source]

Add labels to messages in the currently selected folder.

labels should be a sequence of strings.

Returns the label set for each modified message (see get_gmail_labels), or None if silent is true.

This only works with IMAP servers that support the X-GM-LABELS attribute (eg. Gmail).

append(folder, msg, flags=(), msg_time=None)[source]

Append a message to folder.

msg should be a string contains the full message including headers.

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.

Returns the APPEND response as returned by the server.


Returns the server capability list.

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.


Close the currently selected folder, returning the server response string.

copy(messages, folder)[source]

Copy one or more messages from the current folder to folder. Returns the COPY response string returned by the server.


Create folder on the server returning the server response string.


Delete folder on the server returning the server response string.

delete_messages(messages, silent=False)[source]

Delete one or more messages from the currently selected folder.

Returns the flags set for each modified message (see get_flags).


Activate one or more server side capability extensions.

Most capabilities do not need to be enabled. This is only required for extensions which introduce backwards incompatible behaviour. Two capabilities which may require enable are CONDSTORE and UTF8=ACCEPT.

A list of the requested extensions that were successfully enabled on the server is returned.

Once enabled each extension remains active until the IMAP connection is closed.

See RFC 5161 for more details.


When, no messages are specified, remove all messages from the currently selected folder that have the \Deleted flag set.

The return value is the server response message followed by a list of expunge responses. For example:

('Expunge completed.',
 [(2, 'EXPUNGE'),
  (1, 'EXPUNGE'),
  (0, 'RECENT')])

In this case, the responses indicate that the message with sequence numbers 2 and 1 where deleted, leaving no recent messages in the folder.

See RFC 3501#section-6.4.3 section 6.4.3 and RFC 3501#section-7.4.1 section 7.4.1 for more details.

When messages are specified, remove the specified messages from the selected folder, provided those messages also have the \Deleted flag set. The return value is None in this case.

Expunging messages by id(s) requires that use_uid is True for the client.

See RFC 4315#section-2.1 section 2.1 for more details.

fetch(messages, data, modifiers=None)[source]

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

data should be specified as a sequence 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 sequence of strings if specified, for example ['CHANGEDSINCE 123'].

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).


>> c.fetch([3293, 3230], ['INTERNALDATE', 'FLAGS'])
{3230: {b'FLAGS': (b'\Seen',),
        b'INTERNALDATE': datetime.datetime(2011, 1, 30, 13, 32, 9),
        b'SEQ': 84},
 3293: {b'FLAGS': (),
        b'INTERNALDATE': datetime.datetime(2011, 2, 24, 19, 30, 36),
        b'SEQ': 110}}

Try to locate a special folder, like the Sent or Trash folder.

>>> server.find_special_folder(imapclient.SENT)

This function tries its best to find the correct folder (if any) but uses heuristics when the server is unable to precisely tell where special folders are located.

Returns the name of the folder if found, or None otherwise.


Return True if folder exists on the server.

folder_status(folder, what=None)[source]

Return the status of folder.

what should be a sequence of status items to query. This defaults to ('MESSAGES', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'UNSEEN').

Returns a dictionary of the status items for the folder with keys matching what.


Return the flags set for each message in messages from the currently selected folder.

The return value is a dictionary structured like this: { msgid1: (flag1, flag2, ... ), }.


Return the label set for each message in messages in the currently selected folder.

The return value is a dictionary structured like this: { msgid1: (label1, label2, ... ), }.

This only works with IMAP servers that support the X-GM-LABELS attribute (eg. Gmail).


Get the quotas associated with a mailbox.

Returns a list of Quota objects.


Get the quota roots for a mailbox.

The IMAP server responds with the quota root and the quotas associated so there is usually no need to call get_quota after.

See RFC 2087 for more details.

Return a tuple of MailboxQuotaRoots and list of Quota associated


Returns a list of (who, acl) tuples describing the access controls for folder.

Search using Gmail’s X-GM-RAW attribute.

query should be a valid Gmail search query string. For example: has:attachment in:unread. The search string may be unicode and will be encoded using the specified charset (defaulting to UTF-8).

This method only works for IMAP servers that support X-GM-RAW, which is only likely to be Gmail.

See for more info.


Return True if the IMAP server has the given capability.


Issue the ID command, returning a dict of server implementation fields.

parameters should be specified as a dictionary of field/value pairs, for example: {"name": "IMAPClient", "version": "0.12"}


Put the server into IDLE mode.

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.


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

See RFC 2177 for more information about the IDLE extension.


Check for any IDLE responses sent by the server.

This method should only be called if the server is in IDLE mode (see idle()).

By default, this method will block until an IDLE response is received. If timeout is provided, the call will block for at most this many seconds while waiting for an IDLE response.

The return value is a list of received IDLE responses. These will be parsed with values converted to appropriate types. For example:

[(b'OK', b'Still here'),
 (1, b'EXISTS'),
 (1, b'FETCH', (b'FLAGS', (b'\NotJunk',)))]

Take the server out of IDLE mode.

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'Idle terminated') 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().

list_folders(directory='', pattern='*')[source]

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.

list_sub_folders(directory='', pattern='*')[source]

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

The default behaviour will list all subscribed folders. The directory and pattern arguments are as per list_folders().

login(username, password)[source]

Login using username and password, returning the server response.


Logout, returning the server response.

move(messages, folder)[source]

Atomically move messages to another folder.

Requires the MOVE capability, see RFC 6851.

  • messages – List of message UIDs to move.
  • folder – The destination folder name.
multiappend(folder, msgs)[source]

Append messages to folder using the MULTIAPPEND feature from RFC 3502.

msgs should be a list of strings containing the full message including headers.

Returns the APPEND response from the server.


Return the namespace for the account as a (personal, other, shared) tuple.

Each element may be None if no namespace of that type exists, or a sequence of (prefix, separator) pairs.

For convenience the tuple elements may be accessed positionally or using attributes named personal, other and shared.

See RFC 2342 for more details.


Execute the NOOP command.

This command returns immediately, returning any server side status updates. It can also be used to reset any auto-logout timers.

The return value is the server command response message followed by a list of status responses. For example:

(b'NOOP completed.',
 [(4, b'EXISTS'),
  (3, b'FETCH', (b'FLAGS', (b'bar', b'sne'))),
  (6, b'FETCH', (b'FLAGS', (b'sne',)))])
oauth2_login(user, access_token, mech='XOAUTH2', vendor=None)[source]

Authenticate using the OAUTH2 or XOAUTH2 methods.

Gmail and Yahoo both support the ‘XOAUTH2’ mechanism, but Yahoo requires the ‘vendor’ portion in the payload.

oauthbearer_login(identity, access_token)[source]

Authenticate using the OAUTHBEARER method.

This is supported by Gmail and is meant to supersede the non-standard ‘OAUTH2’ and ‘XOAUTH2’ mechanisms.

plain_login(identity, password, authorization_identity=None)[source]

Authenticate using the PLAIN method (requires server support).

remove_flags(messages, flags, silent=False)[source]

Remove one or more flags from messages in the currently selected folder.

flags should be a sequence of strings.

Returns the flags set for each modified message (see get_flags), or None if silent is true.

remove_gmail_labels(messages, labels, silent=False)[source]

Remove one or more labels from messages in the currently selected folder, or None if silent is true.

labels should be a sequence of strings.

Returns the label set for each modified message (see get_gmail_labels).

This only works with IMAP servers that support the X-GM-LABELS attribute (eg. Gmail).

rename_folder(old_name, new_name)[source]

Change the name of a folder on the server.

sasl_login(mech_name, mech_callable)[source]

Authenticate using a provided SASL mechanism (requires server support).

The mech_callable will be called with one parameter (the server challenge as bytes) and must return the corresponding client response (as bytes, or as string which will be automatically encoded).

It will be called as many times as the server produces challenges, which will depend on the specific SASL mechanism. (If the mechanism is defined as “client-first”, the server will nevertheless produce a zero-length challenge.)

For example, PLAIN has just one step with empty challenge, so a handler might look like this:

plain_mech = lambda _: “0%s0%s” % (username, password)

imap.sasl_login(“PLAIN”, plain_mech)

A more complex but still stateless handler might look like this:

def example_mech(challenge):
if challenge == b”Username:”
return username.encode(“utf-8”)
elif challenge == b”Password:”
return password.encode(“utf-8”)
return b””

imap.sasl_login(“EXAMPLE”, example_mech)

A stateful handler might look like this:

class ScramSha256SaslMechanism():
def __init__(self, username, password):
def __call__(self, challenge):

self.step += 1 if self.step == 1:

response = …
elif self.step == 2:
response = …

return response

scram_mech = ScramSha256SaslMechanism(username, password)

imap.sasl_login(“SCRAM-SHA-256”, scram_mech)

search(criteria='ALL', charset=None)[source]

Return a list of messages ids from the currently selected folder matching criteria.

criteria should be a sequence of one or more criteria items. Each criteria item may be either unicode or bytes. Example values:

[u'SMALLER', 500]
[b'NOT', b'DELETED']
[u'TEXT', u'foo bar', u'FLAGGED', u'SUBJECT', u'baz']
[u'SINCE', date(2005, 4, 3)]

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:

u'SMALLER 500'
u'TEXT "foo bar" FLAGGED SUBJECT "baz"'
b'SINCE 03-Apr-2005'

To support complex search expressions, criteria lists can be nested. IMAPClient will insert parentheses in the right places. The following will match messages that are both not flagged and do not have “foo” in the subject:

[‘NOT’, [‘SUBJECT’, ‘foo’, ‘FLAGGED’]]

charset specifies the character set of the criteria. It defaults to US-ASCII as this is the only charset that a server is required to support by the RFC. UTF-8 is commonly supported however.

Any criteria specified using unicode will be encoded as per charset. Specifying a unicode criteria that can not be encoded using charset will result in an error.

Any criteria specified using bytes will be sent as-is but should use an encoding that matches charset (the character set given is still passed on to the server).

See RFC 3501#section-6.4.4 for more details.

Note that criteria arguments that are 8-bit will be transparently sent by IMAPClient as IMAP literals to ensure adherence to IMAP standards.

The returned list of message ids will have a special modseq attribute. This is set if the server included a MODSEQ value to the search response (i.e. if a MODSEQ criteria was included in the search).

select_folder(folder, readonly=False)[source]

Set the current folder on the server.

Future calls to methods such as search and fetch will act on the selected folder.

Returns a dictionary containing the SELECT response. At least the b'EXISTS', b'FLAGS' and b'RECENT' keys are guaranteed to exist. An example:

{b'EXISTS': 3,
 b'FLAGS': (b'\Answered', b'\Flagged', b'\Deleted', ... ),
 b'RECENT': 0,
 b'PERMANENTFLAGS': (b'\Answered', b'\Flagged', b'\Deleted', ... ),
 b'READ-WRITE': True,
 b'UIDNEXT': 11,
 b'UIDVALIDITY': 1239278212}
set_flags(messages, flags, silent=False)[source]

Set the flags for messages in the currently selected folder.

flags should be a sequence of strings.

Returns the flags set for each modified message (see get_flags), or None if silent is true.

set_gmail_labels(messages, labels, silent=False)[source]

Set the labels for messages in the currently selected folder.

labels should be a sequence of strings.

Returns the label set for each modified message (see get_gmail_labels), or None if silent is true.

This only works with IMAP servers that support the X-GM-LABELS attribute (eg. Gmail).


Set one or more quotas on resources.

Parameters:quotas – list of Quota objects
setacl(folder, who, what)[source]

Set an ACL (what) for user (who) for a folder.

Set what to an empty string to remove an ACL. Returns the server response string.


Close the connection to the IMAP server (without logging out)

In most cases, logout() should be used instead of this. The logout method also shutdown down the connection.

sort(sort_criteria, criteria='ALL', charset='UTF-8')[source]

Return a list of message ids from the currently selected folder, sorted by sort_criteria and optionally filtered by criteria.

sort_criteria may be specified as a sequence of strings or a single string. IMAPClient will take care any required conversions. Valid sort_criteria values:


The criteria and charset arguments are as per search().

See RFC 5256 for full details.

Note that SORT is an extension to the IMAP4 standard so it may not be supported by all IMAP servers.


Switch to an SSL encrypted connection by sending a STARTTLS command.

The ssl_context argument is optional and should be a 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.


Subscribe to folder, returning the server response string.

thread(algorithm='REFERENCES', criteria='ALL', charset='UTF-8')[source]

Return a list of messages threads from the currently selected folder which match criteria.

Each returned thread is a list of messages ids. An example return value containing three message threads:

((1, 2), (3,), (4, 5, 6))

The optional algorithm argument specifies the threading algorithm to use.

The criteria and charset arguments are as per search().

See RFC 5256 for more details.


Unselect the current folder and release associated resources.

Unlike close_folder, the UNSELECT command does not expunge the mailbox, keeping messages with Deleted flag set for example.

Returns the UNSELECT response string returned by the server.


Unsubscribe to folder, returning the server response string.


access the server greeting message

xlist_folders(directory='', pattern='*')[source]

Execute the XLIST command, returning (flags, delimiter, name) tuples.

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.

A XLIST response could look something like:

[((b'\HasNoChildren', b'\Inbox'), b'/', u'Inbox'),
 ((b'\Noselect', b'\HasChildren'), b'/', u'[Gmail]'),
 ((b'\HasNoChildren', b'\AllMail'), b'/', u'[Gmail]/All Mail'),
 ((b'\HasNoChildren', b'\Drafts'), b'/', u'[Gmail]/Drafts'),
 ((b'\HasNoChildren', b'\Important'), b'/', u'[Gmail]/Important'),
 ((b'\HasNoChildren', b'\Sent'), b'/', u'[Gmail]/Sent Mail'),
 ((b'\HasNoChildren', b'\Spam'), b'/', u'[Gmail]/Spam'),
 ((b'\HasNoChildren', b'\Starred'), b'/', u'[Gmail]/Starred'),
 ((b'\HasNoChildren', b'\Trash'), b'/', u'[Gmail]/Trash')]

This is a deprecated Gmail-specific IMAP extension (See for more information).

The directory and pattern arguments are as per list_folders().

class imapclient.SocketTimeout[source]

Represents timeout configuration for an IMAP connection.

  • connect – maximum time to wait for a connection attempt to remote server
  • read – maximum time to wait for performing a read/write operation

As an example, SocketTimeout(connect=15, read=60) will make the socket timeout if the connection takes more than 15 seconds to establish but read/write operations can take up to 60 seconds once the connection is done.

Fetch Response Types

Various types may be used in the data structures returned by IMAPClient.fetch() when certain response types are encountered during parsing.

class imapclient.response_types.Address[source]

Represents electronic mail addresses. Used to store addresses in Envelope.

  • name – The address “personal name”.
  • route – SMTP source route (rarely used).
  • mailbox – Mailbox name (what comes just before the @ sign).
  • host – The host/domain name.

As an example, an address header that looks like:

Mary Smith <>

would be represented as:

Address(name=u'Mary Smith', route=None, mailbox=u'mary', host=u'')

See RFC 2822 for more detail.

See also Envelope for information about handling of “group syntax”.

class imapclient.response_types.BodyData[source]

Returned when parsing BODY and BODYSTRUCTURE responses.

class imapclient.response_types.Envelope[source]

Represents envelope structures of messages. Returned when parsing ENVELOPE responses.

  • date – A datetime instance that represents the “Date” header.
  • subject – A string that contains the “Subject” header.
  • from_ – A tuple of Address objects that represent one or more addresses from the “From” header, or None if header does not exist.
  • sender – As for from_ but represents the “Sender” header.
  • reply_to – As for from_ but represents the “Reply-To” header.
  • to – As for from_ but represents the “To” header.
  • cc – As for from_ but represents the “Cc” header.
  • bcc – As for from_ but represents the “Bcc” recipients.
  • in_reply_to – A string that contains the “In-Reply-To” header.
  • message_id – A string that contains the “Message-Id” header.

A particular issue to watch out for is IMAP’s handling of “group syntax” in address fields. This is often encountered as a recipient header of the form:


but can also be expressed per this more general example:

A group:, B <>;

This example would yield the following Address tuples:

Address(name=None, route=None, mailbox=u'A group', host=None)
Address(name=None, route=None, mailbox=u'a', host=u'')
Address(name=u'B', route=None, mailbox=u'b', host=u'')
Address(name=None, route=None, mailbox=None, host=None)

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.

See RFC 3501#section-7.4.2 and RFC 2822 for further details.

class imapclient.response_types.SearchIds(*args)[source]

Contains a list of message ids as returned by

The modseq attribute will contain the MODSEQ value returned by the server (only if the SEARCH command sent involved the MODSEQ criteria). See RFC 4551 for more details.


IMAPClient wraps exceptions raised by imaplib to ease the error handling. All the exceptions related to IMAP errors are defined in the module imapclient.exceptions. The following general exceptions may be raised:

  • IMAPClientError: the base class for IMAPClient’s exceptions and the most commonly used error.
  • IMAPClientAbortError: raised if a serious error has occurred that means the IMAP connection is no longer usable. The connection should be dropped without logout if this occurs.
  • IMAPClientReadOnlyError: raised if a modifying operation was attempted on a read-only folder.

More specific exceptions existed for common known errors:

exception imapclient.exceptions.CapabilityError[source]

The command tried by the user needs a capability not installed on the IMAP server

exception imapclient.exceptions.IllegalStateError[source]

The command tried needs a different state to be executed. This means the user is not logged in or the command needs a folder to be selected.

exception imapclient.exceptions.InvalidCriteriaError[source]

A command using a search criteria failed, probably due to a syntax error in the criteria string.

exception imapclient.exceptions.LoginError[source]

A connection has been established with the server but an error occurred during the authentication.

exception imapclient.exceptions.ProtocolError[source]

The server replied with a response that violates the IMAP protocol.

Exceptions from lower layers are possible, such as networks error or unicode malformed exception. In particular:

  • socket.error
  • socket.timeout: raised if a timeout was specified when creating the IMAPClient instance and a network operation takes too long.
  • ssl.SSLError: the base class for network or SSL protocol errors when ssl=True or starttls() is used.
  • ssl.CertificateError: raised when TLS certification verification fails. This is not a subclass of SSLError.


class imapclient.testable_imapclient.MockIMAP4(*args, **kwargs)[source]
class imapclient.testable_imapclient.TestableIMAPClient[source]

Wrapper of imapclient.IMAPClient that mocks all interaction with real IMAP server.

This class should only be used in tests, where you can safely interact with imapclient without running commands on a real IMAP account.

TLS Support

This module contains IMAPClient’s functionality related to Transport Layer Security (TLS a.k.a. SSL).

class imapclient.tls.IMAP4_TLS(host, port, ssl_context, timeout=None)[source]

IMAP4 client class for TLS/SSL connections.

Adapted from imaplib.IMAP4_SSL.

open(host, port=993, timeout=None)[source]
Setup connection to remote server on “host:port”
(default: localhost:standard IMAP4 port).
This connection will be used by the routines:
read, readline, send, shutdown.

Read ‘size’ bytes from remote.


Read line from remote.


Send data to remote.


Close I/O established in “open”.

Thread Safety

Instances of IMAPClient are NOT thread safe. They should not be shared and accessed concurrently from multiple threads.