IMAPClient

Author:Menno Smits
Version:1.0-alpha
Date:September 01, 2015
Homepage:http://imapclient.freshfoo.com
Download:http://pypi.python.org/pypi/IMAPClient/
Documentation:http://imapclient.readthedocs.org/
License:New BSD License
Support:Mailing List

Introduction

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.

Python versions 2.6, 2.7, 3.3 and 3.4 are officially supported.

A Simple Example

The core of the IMAPClient API is the IMAPClient class. Instantiating this class, creates a connection to an IMAP account. Calling methods on the IMAPClient instance interacts with the server.

The following example shows a simple interaction with an IMAP server. It displays the message ID, size and IMAP flags of all non-deleted messages in the INBOX folder.

# Copyright (c) 2014, Menno Smits
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses

from __future__ import unicode_literals

from imapclient import IMAPClient

HOST = 'imap.host.com'
USERNAME = 'someuser'
PASSWORD = 'secret'
ssl = False

server = IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME, PASSWORD)

select_info = server.select_folder('INBOX')
print('%d messages in INBOX' % select_info['EXISTS'])

messages = server.search(['NOT', 'DELETED'])
print("%d messages that aren't deleted" % len(messages))

print()
print("Messages:")
response = server.fetch(messages, ['FLAGS', 'RFC822.SIZE'])
for msgid, data in response.iteritems():
    print('   ID %d: %d bytes, flags=%s' % (msgid,
                                            data[b'RFC822.SIZE'],
                                            data[b'FLAGS']))

The output from this example could look something like this

96 messages in INBOX
75 messages that aren't deleted

Messages:
   ID 38273: 1775 bytes, flags=(b'NonJunk',)
   ID 36459: 2833 bytes, flags=(b'\\Flagged', v'\\Seen')
   ID 34693: 2874 bytes, flags=(b'\\Flagged', v'\\Seen')
   ID 38066: 5368 bytes, flags=(b'\\Flagged', v'\\Seen')
   ID 38154: 9079 bytes, flags=(b'\\Seen', b'NonJunk')
   ID 14099: 3322 bytes, flags=(b'\\Flagged', b'\\Seen', b'$Label1')
   ID 34196: 9163 bytes, flags=(b'\\Answered', b'\\Seen')
   ID 35349: 4266 bytes, flags=(b'\\Flagged', b'\\Seen')
   ID 29335: 5617 bytes, flags=(b'\\Flagged', b'\\Seen', b'NonJunk')
   ID 38041: 7649 bytes, flags=(b'\\Seen', b'NonJunk')
   ID 22310: 976108 bytes, flags=(b'\\Flagged', b'\\Seen', b'$Label1')
   ID 6439: 3792 bytes, flags=(b'\\Flagged', b'\\Seen', b'$Label1', b'Junk')

Concepts

Message Identifiers

There are two ways to refer to messages using the IMAP protocol.

One way is by message sequence number where the messages in a mailbox are numbered from 1 to N where N is the number of messages. These numbers don’t persist between sessions and may be reassigned after some operations such as a folder 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.

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. 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:*'). Whether these are interpreted as message sequence numbers or UIDs depends on 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.

Message Flags

An IMAP server keeps zero or more flags for each message. These indicate certain properties of the message or can be used by IMAP clients to keep track of data related to a message.

The IMAPClient package has constants for a number of commmonly used flags:

DELETED = br'\Deleted'
SEEN = br'\Seen'
ANSWERED = br'\Answered'
FLAGGED = br'\Flagged'
DRAFT = br'\Draft'
RECENT = br'\Recent'         # This flag is read-only

Any method that accepts message flags takes either a sequence containing message flags (eg. [DELETED, 'foo', 'Bar']) or a single message flag (eg. 'Foo').

Folder Name Encoding

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

Exceptions

The IMAP related exceptions that will be raised by this class are:

  • IMAPClient.Error
  • IMAPClient.AbortError
  • IMAPClient.ReadOnlyError

These are aliases for the imaplib.IMAP4 exceptions of the same name. Socket errors may also be raised in the case of network errors.

TLS/SSL

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.

# Copyright (c) 2015, Menno Smits
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses

from __future__ import unicode_literals
import imapclient
from backports import ssl

HOST = 'imap.host.com'
USERNAME = 'someuser'
PASSWORD = 'secret'

context = imapclient.create_default_context()

# don't check if certificate hostname doesn't match target hostname
context.check_hostname = False

# don't check if the certificate is trusted by a certificate authority
context.verify_mode = ssl.CERT_NONE

server = imapclient.IMAPClient(HOST, use_uid=True, ssl=True, ssl_context=context)
server.login(USERNAME, PASSWORD)
# ...

The next example shows how to create a context that will use custom CA certificate. This is required to perform verification of a self-signed certificate used by the IMAP server.

# Copyright (c) 2015, Menno Smits
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses

from __future__ import unicode_literals
import imapclient

HOST = 'imap.host.com'
USERNAME = 'someuser'
PASSWORD = 'secret'

context = imapclient.create_default_context(cafile="/path/to/cacert.pem")

server = imapclient.IMAPClient(HOST, use_uid=True, ssl=True, ssl_context=context)
server.login(USERNAME, PASSWORD)
# ...

The above examples show some of the most common TLS parameter customisations but there are many other tweaks are possible. Consult the Python 3 ssl package documentation for further options.

Using gevent with IMAPClient

Some extra monkey patching is required to let gevent work with pyOpenSSL (used by IMAPClient for TLS support). The gevent_openssl package performs this patching and can be used with IMAPClient like this:

from gevent import monkey; monkey.patch_all()
import gevent_openssl; gevent_openssl.monkey_patch()

import imapclient

client = imapclient.IMAPClient(...)
...

API Reference

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=False, 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 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.

add_flags(messages, flags)[source]

Add flags to messages.

flags should be a sequence of strings.

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

add_gmail_labels(messages, labels)[source]

Add labels to messages.

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

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.

capabilities()[source]

Returns the server capability list.

If the session is authenticated and the server has returned a 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 cached capabilities determined at connection time will be returned.

close_folder()[source]

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(folder)[source]

Create folder on the server returning the server response string.

delete_folder(folder)[source]

Delete folder on the server returning the server response string.

delete_messages(messages)[source]

Delete one or more messages from the currently selected folder.

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

expunge()[source]

Remove any 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.

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

Retrieve selected data associated with one or more messages.

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

Example:

>> 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}}
folder_exists(folder)[source]

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.

get_flags(messages)[source]

Return the flags set for each message in messages.

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

get_gmail_labels(messages)[source]

Return the label set for each message in messages.

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

getacl(folder)[source]

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 https://developers.google.com/gmail/imap_extensions#extension_of_the_search_command_x-gm-raw for more info.

has_capability(capability)[source]

Return True if the IMAP server has the given capability.

id_(parameters=None)[source]

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"}

idle()[source]

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.

Note

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

See RFC 2177 for more information about the IDLE extension.

idle_check(timeout=None)[source]

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',)))]
idle_done()[source]

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=u'', pattern=u'*')[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=u'', pattern=u'*')[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()[source]

Logout, returning the server response.

namespace()[source]

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.

noop()[source]

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=u'XOAUTH2', vendor=None)[source]

Authenticate using the OAUTH2 method.

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

oauth_login(url, oauth_token, oauth_token_secret, consumer_key=u'anonymous', consumer_secret=u'anonymous')[source]

Authenticate using the OAUTH method.

This only works with IMAP servers that support OAUTH (e.g. Gmail).

remove_flags(messages, flags)[source]

Remove one or more flags from messages.

flags should be a sequence of strings.

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

remove_gmail_labels(messages, labels)[source]

Remove one or more labels from messages.

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.

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

Return a list of messages ids 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'UNSEEN']
[u'SMALLER', 500]
[b'NOT', b'DELETED']
[u'TEXT', u'foo bar', u'FLAGGED', u'SUBJECT', u'baz']

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'UNSEEN'
u'SMALLER 500'
b'NOT DELETED'
u'TEXT "foo bar" FLAGGED SUBJECT "baz"'

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)[source]

Set the flags for messages.

flags should be a sequence of strings.

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

set_gmail_labels(messages, labels)[source]

Set the labels for messages.

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

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.

shutdown()[source]

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=u'ALL', charset=u'UTF-8')[source]

Return a list of message ids 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:

['ARRIVAL']
['SUBJECT', 'ARRIVAL']
'ARRIVAL'
'REVERSE SIZE'

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.

starttls(ssl_context=None)[source]

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

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.

subscribe_folder(folder)[source]

Subscribe to folder, returning the server response string.

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

Return a list of messages threads matching 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.

unsubscribe_folder(folder)[source]

Unsubscribe to folder, returning the server response string.

xlist_folders(directory=u'', pattern=u'*')[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 https://developers.google.com/gmail/imap_extensions#xlist_is_deprecated for more information). It is the responsibility of the caller to either check for XLIST in the server capabilites, or to handle the error if the server doesn’t support this extension.

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

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.

Variables:
  • 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 <mary@foo.com>

would be represented as:

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

See RFC 2822 for more.

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.

Variables:
  • 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 on 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.
class imapclient.response_types.SearchIds(*args)[source]

Contains a list of message ids as returned by IMAPClient.search().

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.

TLS Support

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

It uses backports.ssl to provide consistent TLS functionality across Python versions.

imapclient.tls.create_default_context(cafile=None, capath=None, cadata=None)[source]

Return a backports.ssl.SSLContext object configured with sensible default settings.

The optional cafile argument is path to a file of concatenated CA certificates in PEM format.

The optional capath argument is a path to a directory containing several CA certificates in PEM format, following an OpenSSL specific layout.

The optional cadata argument is either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates.

If cafile, capath and cadata are all None then system-installed CA certificates will be loaded (if available).

Interactive Sessions

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.

The connected IMAPClient instance is available as the variable “c”.

If installed, IPython will be used as the embedded shell. Otherwise the basic built-in Python shell will be used.

Here’s an example session:

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

IMAPClient instance is "c"
In [1]: c.select_folder('inbox')
Out[1]:
{b'EXISTS': 2,
 b'FLAGS': (b'\\Answered',
     b'\\Flagged',
     b'\\Deleted',
     b'\\Seen',
     b'\\Draft'),
 b'PERMANENTFLAGS': (b'\\Answered',
     b'\\Flagged',
     b'\\Deleted',
     b'\\Seen',
     b'\\Draft'),
 b'READ-WRITE': True,
 b'RECENT': 0,
 b'UIDNEXT': 1339,
 b'UIDVALIDITY': 1239278212}

In [2]: c.search()
Out[2]: [1123, 1233]

In [3]: c.logout()
Out[3]: b'Logging out'

External Documentation

The Unofficial IMAP Protocol Wiki is very useful when writing IMAP related software and is highly recommended.