21
IMAPClient Documentation Release 0.9.2 Menno Smits March 28, 2013

IMAPClient Documentation · 2019. 4. 2. · IMAPClient Documentation, Release 0.9.2 msg_time is an optional datetime instance specifying the date and time to set on the message. The

  • Upload
    others

  • View
    18

  • Download
    0

Embed Size (px)

Citation preview

  • IMAPClient DocumentationRelease 0.9.2

    Menno Smits

    March 28, 2013

  • CONTENTS

    i

  • ii

  • IMAPClient Documentation, Release 0.9.2

    Author Menno Smits

    Version 0.9.2

    Date March 28, 2013

    Homepage http://imapclient.freshfoo.com

    Download http://pypi.python.org/pypi/IMAPClient/

    Documentation http://imapclient.readthedocs.org/

    License New BSD License

    Support Mailing List

    CONTENTS 1

    http://freshfoo.comhttp://imapclient.freshfoo.comhttp://pypi.python.org/pypi/IMAPClient/http://imapclient.readthedocs.org/http://en.wikipedia.org/wiki/BSD_licenseshttp://librelist.com/browser/imapclient/

  • IMAPClient Documentation, Release 0.9.2

    2 CONTENTS

  • CHAPTER

    ONE

    INTRODUCTION

    IMAPClient is a a Pythonic, easy-to-use IMAP client package.

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

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

    3

    http://www.faqs.org/rfcs/rfc3501.html

  • IMAPClient Documentation, Release 0.9.2

    4 Chapter 1. Introduction

  • CHAPTER

    TWO

    A SIMPLE EXAMPLE

    The core of the IMAPClient API is the IMAPClient class. Instantiating this class, creates a connection to an IMAPaccount. 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 IMAPflags of all non-deleted messages in the INBOX folder.

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

    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)

    printprint "Messages:"response = server.fetch(messages, [’FLAGS’, ’RFC822.SIZE’])for msgid, data in response.iteritems():

    print ’ ID %d: %d bytes, flags=%s’ % (msgid,data[’RFC822.SIZE’],data[’FLAGS’])

    The output from this example could look something like this

    96 messages in INBOX75 messages that aren’t deleted

    Messages:ID 38273: 1775 bytes, flags=(’NonJunk’,)ID 36459: 2833 bytes, flags=(’\\Flagged’, ’\\Seen’)ID 34693: 2874 bytes, flags=(’\\Flagged’, ’\\Seen’)ID 38066: 5368 bytes, flags=(’\\Flagged’, ’\\Seen’)

    5

  • IMAPClient Documentation, Release 0.9.2

    ID 38154: 9079 bytes, flags=(’\\Seen’, ’NonJunk’)ID 14099: 3322 bytes, flags=(’\\Flagged’, ’\\Seen’, ’$Label1’)ID 34196: 9163 bytes, flags=(’\\Answered’, ’\\Seen’)ID 35349: 4266 bytes, flags=(’\\Flagged’, ’\\Seen’)ID 29335: 5617 bytes, flags=(’\\Flagged’, ’\\Seen’, ’NonJunk’)ID 38041: 7649 bytes, flags=(’\\Seen’, ’NonJunk’)ID 22310: 976108 bytes, flags=(’\\Flagged’, ’\\Seen’, ’$Label1’)ID 6439: 3792 bytes, flags=(’\\Flagged’, ’\\Seen’, ’$Label1’, ’Junk’)

    6 Chapter 2. A Simple Example

  • CHAPTER

    THREE

    CONCEPTS

    3.1 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 thenumber of messages. These numbers don’t persist between sessions and may be reassigned after some operations suchas a folder expunge.

    A more convenient approach is Unique Identifiers (UIDs). Unique Identifiers are integers assigned to each messageby 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 returnvalues. 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 singlemessage 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 UIDsdepends on the use_uid argument passed when an IMAPClient instance is created and the use_uid attribute. Theuse_uid attribute can be used to change the message id type between calls to the server.

    3.2 Message Flags

    An IMAP server keeps zero or more flags for each message. These indicate certain properties of the message or canbe 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 = r’\Deleted’SEEN = r’\Seen’ANSWERED = r’\Answered’FLAGGED = r’\Flagged’DRAFT = r’\Draft’RECENT = r’\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’).

    7

  • IMAPClient Documentation, Release 0.9.2

    3.3 Folder Name Encoding

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

    All folder names returned by IMAPClient are always returned as unicode strings.

    The ampersand character (“&”) has special meaning in IMAP folder names. IMAPClient automatically escapes andunescapes 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 defaultsto True.

    3.4 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 ofnetwork errors.

    8 Chapter 3. Concepts

    http://tools.ietf.org/html/rfc3501#section-5.1.3

  • CHAPTER

    FOUR

    IMAPCLIENT CLASS REFERENCE

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

    class imapclient.IMAPClient(host, port=None, use_uid=True, ssl=False, stream=False)A connection to the IMAP server specified by host is made when the 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 stream is True then host is used as the command to run to establish a connection to the IMAP server (defaultsto False). This is useful for exotic connection or authentication setups.

    The normalise_times attribute specifies whether datetimes returned by fetch() are normalised to the localsystem 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 canbe 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 disablesdebug output and 5 enables full output with wire logging and parsing logs. True and False can also beassigned 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 forwriting debug output to.

    add_flags(messages, flags)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)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)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.

    9

  • IMAPClient Documentation, Release 0.9.2

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

    Returns the APPEND response as returned by the server.

    capabilities()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, withthe results cached for future calls.

    If the session is not yet authenticated, the cached capabilities determined at connection time will be re-turned.

    close_folder()Close the currently selected folder, returning the server response string.

    copy(messages, folder)Copy one or more messages from the current folder to folder. Returns the COPY response string returnedby the server.

    create_folder(folder)Create folder on the server returning the server response string.

    delete_folder(folder)Delete folder on the server returning the server response string.

    delete_messages(messages)Delete one or more messages from the currently selected folder.

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

    expunge()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, leavingno recent messages in the folder.

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

    fetch(messages, data, modifiers=None)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 asequnce 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.

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

    10 Chapter 4. IMAPClient Class Reference

    http://tools.ietf.org/html/rfc3501#section-6.4.3http://tools.ietf.org/html/rfc3501#section-7.4.1

  • IMAPClient Documentation, Release 0.9.2

    Example:

    >> c.fetch([3293, 3230], [’INTERNALDATE’, ’FLAGS’]){3230: {’FLAGS’: (’\Seen’,),

    ’INTERNALDATE’: datetime.datetime(2011, 1, 30, 13, 32, 9),’SEQ’: 84},

    3293: {’FLAGS’: (),’INTERNALDATE’: datetime.datetime(2011, 2, 24, 19, 30, 36),’SEQ’: 110}}

    folder_exists(folder)Return True if folder exists on the server.

    folder_status(folder, what=None)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)Return the flags set for each message in messages.

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

    get_folder_delimiter()Return the folder separator used by the IMAP server.

    Warning: The implementation just picks the first folder separator from the first namespace returned.This is not particularly sensible. Use namespace instead().

    get_gmail_labels(messages)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)Returns a list of (who, acl) tuples describing the access controls for folder.

    has_capability(capability)Return True if the IMAP server has the given capability.

    idle()Put the server into IDLE mode.

    In this mode the server will return unsolicited responses about changes to the selected mailbox. Thismethod returns immediately. Use idle_check() to look for IDLE responses and idle_done() tostop 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)Check for any IDLE responses sent by the server.

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

    11

    http://tools.ietf.org/html/rfc2177

  • IMAPClient Documentation, Release 0.9.2

    By default, this method will block until an IDLE response is received. If timeout is provided, the call willblock 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 toappropriate types. For example:

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

    idle_done()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 isthe text sent by the server when the IDLE command finished (eg. ’Idle terminated’) andidle_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=’*’)Get a listing of folders on the server as a list of (flags, delimiter, name) tuples.

    Calling list_folders with no arguments will list all folders.

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

    Folder names are always returned as unicode strings except if folder_decode is not set.

    list_sub_folders(directory=’‘, pattern=’*’)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 perlist_folders().

    login(username, password)Login using username and password, returning the server response.

    logout()Logout, returning the server response.

    namespace()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, otherand shared.

    See RFC 2342 for more details.

    noop()Execute the NOOP command.

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

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

    12 Chapter 4. IMAPClient Class Reference

    http://tools.ietf.org/html/rfc2342

  • IMAPClient Documentation, Release 0.9.2

    (’NOOP completed.’,[(4, ’EXISTS’),(3, ’FETCH’, (’FLAGS’, (’bar’, ’sne’))),(6, ’FETCH’, (’FLAGS’, (’sne’,)))])

    oauth2_login(user, access_token)Authenticate using the OAUTH2 method.

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

    oauth_login(url, oauth_token, oauth_token_secret, consumer_key=’anonymous’, con-sumer_secret=’anonymous’)

    Authenticate using the OAUTH method.

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

    remove_flags(messages, flags)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)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)Change the name of a folder on the server.

    search(criteria=’ALL’, charset=None)Return a list of messages ids matching criteria.

    criteria should be a list of of one or more criteria specifications or a single critera string. Example valuesinclude:

    ’NOT DELETED’’UNSEEN’’SINCE 1-Feb-2011’

    charset specifies the character set of the strings in the criteria. It defaults to US-ASCII.

    See RFC 3501 section 6.4.4 for more details.

    select_folder(folder, readonly=False)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 EXISTS, FLAGS and RECENT keysare guaranteed to exist. An example:

    {’EXISTS’: 3,’FLAGS’: (’\Answered’, ’\Flagged’, ’\Deleted’, ... ),’RECENT’: 0,’PERMANENTFLAGS’: (’\Answered’, ’\Flagged’, ’\Deleted’, ... ),’READ-WRITE’: True,’UIDNEXT’: 11,’UIDVALIDITY’: 1239278212}

    13

    http://tools.ietf.org/html/rfc3501#section-6.4.4

  • IMAPClient Documentation, Release 0.9.2

    set_flags(messages, flags)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)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)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.

    sort(sort_criteria, criteria=’ALL’, charset=’UTF-8’)Return a list of message ids sorted by sort_criteria and optionally filtered by criteria.

    Example values for sort_criteria include:

    ARRIVALREVERSE SIZESUBJECT

    The criteria argument is 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.

    subscribe_folder(folder)Subscribe to folder, returning the server response string.

    thread(algorithm=’REFERENCES’, criteria=’ALL’, charset=’UTF-8’)Return a list of messages threads matching criteria.

    Each thread is a list of messages ids.

    See RFC 5256 for more details.

    unsubscribe_folder(folder)Unsubscribe to folder, returning the server response string.

    xlist_folders(directory=’‘, pattern=’*’)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 ofthe inbox may be localized and the flags can be used to determine the actual inbox, even if the name hasbeen localized.

    A XLIST response could look something like:

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

    14 Chapter 4. IMAPClient Class Reference

    http://tools.ietf.org/html/rfc5256https://tools.ietf.org/html/rfc5256

  • IMAPClient Documentation, Release 0.9.2

    This is a Gmail-specific IMAP extension. It is the responsibility of the caller to either check for XLIST inthe 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().

    15

  • IMAPClient Documentation, Release 0.9.2

    16 Chapter 4. IMAPClient Class Reference

  • CHAPTER

    FIVE

    INTERACTIVE SESSIONS

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

    Start a session like this:

    python -m imapclient.interact -H -u ...

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

    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 -u ...Connecting...Connected.

    IMAPClient instance is "c"In [1]: c.select_folder(’inbox’)Out[1]:{’EXISTS’: 2,’FLAGS’: (’\\Answered’,’\\Flagged’,’\\Deleted’,’\\Seen’,’\\Draft’),

    ’PERMANENTFLAGS’: (’\\Answered’,’\\Flagged’,’\\Deleted’,’\\Seen’,’\\Draft’),

    ’READ-WRITE’: True,’RECENT’: 0,’UIDNEXT’: 1339,’UIDVALIDITY’: 1239278212}

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

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

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

    17