IMAPClient Documentation

repository·master·Indexed 20 days ago

https://github.com/mjs/imapclient

A high-level, Pythonic IMAP client library that simplifies interaction with IMAP servers. It provides fully parsed responses, transparent UID handling, and easy-to-use search and fetch methods, wrapping the standard imaplib module to offer a more manageable exception hierarchy and a cleaner API.

Tokens
4.7K
Snippets
17
Records
27
Agent score
69%

What's inside IMAPClient

  1. Understand Message Identifiers (UIDs vs Sequence Numbers)

    master

    IMAP messages are identified in two ways:

    1. Message Sequence Numbers: Integers from 1 to N (the total number of messages in a folder). These are volatile and can change if messages are deleted or expunged.
    2. Unique Identifiers (UIDs): Integers assigned by the server that persist across sessions and remain stable even after expunging.

    Configuration:

    • IMAPClient uses UIDs by default.
    • You can control this behavior using the use_uid argument during instantiation or by modifying the use_uid attribute on an existing instance.

    Usage Patterns: Methods accepting message IDs can take:

    • A single integer: 123
    • A sequence of integers: [1, 2, 3]
    • A string representing IMAP ranges/sets: '50-65', '2:*', or '2,4:7,9,12:*'
    # Using UIDs (default)
    client = IMAPClient('imap.example.com', use_uid=True)
    
    # Switching to sequence numbers for a specific operation
    client.use_uid = False
    client.fetch('[1:5]', ['BODY[]'])
    
    # Using range strings
    client.add('/Seen', '1:10')
  2. What makes IMAPClient different from imaplib

    master

    While IMAPClient uses the Python standard library's imaplib module under the hood, it provides a more Pythonic API.

    Main differences:

    1. Automatic Parsing: It performs the extra parsing work for you, returning readily usable objects rather than raw bytes.
    2. Error Handling: It uses exceptions for error states, eliminating the need for manual error checking of return values.
    3. Data Types: It converts IMAP responses into sensible Python types.
  3. Handle Folder Name Encoding

    master

    IMAPClient handles folder name encoding automatically to support Unicode characters (e.g., non-English characters) using modified UTF-7. It also automatically escapes and unescapes the ampersand (&) character, which has special meaning in IMAP.

    Configuration:

    • The folder_encode attribute controls this behavior (defaults to True).
    • If True: Folder names returned by IMAPClient are always Unicode strings.
    • If False: Folder names are returned as str (Python 2) or bytes (Python 3).
  4. Understand IMAPClient thread safety

    master
    Instances of IMAPClient are NOT thread safe. Do not share a single IMAPClient instance across multiple threads or access it concurrently. Each thread should manage its own instance to avoid race conditions and protocol errors.
  5. Watch a mailbox using the IDLE extension

    master

    The IDLE extension allows an IMAP server to notify the client of mailbox changes in real-time, serving as an alternative to polling. To use it, connect to the server, select a mailbox, and enter IDLE mode. The server will send notifications until the client issues a DONE command.

    Important Note: IMAPClient does not automatically handle low-level socket errors for long-lived connections. It is recommended to renew the IDLE command every 10 minutes to prevent the connection from being abruptly closed by the server.

  6. Interpret fetch response types

    master
    When calling IMAPClient.fetch, the returned data structures may contain various parsed response types. These types are defined in the imapclient.response_types module and are used to represent the different kinds of data (e.g., body parts, flags, etc.) encountered during parsing.
  7. Clean up IMAP connections using context managers

    master

    To prevent memory leaks and file descriptor exhaustion in long-lived processes, you must ensure IMAP connections are closed. While you can manually call the logout() method, it is safer to use IMAPClient as a context manager. This ensures the connection is automatically closed even if an error occurs during a session (e.g., during select_folder()).

    import imapclient
    
    with imapclient.IMAPClient(host="imap.foo.org") as c:
        c.login("bar@foo.org", "passwd")
        c.select_folder("INBOX")
  8. Basic usage of IMAPClient

    master

    The core of the library is the IMAPClient class. Instantiating this class creates a connection to an IMAP account. You can then use methods like login, select_folder, search, and fetch to interact with the server.

    Key features include:

    • Parsed Responses: Unlike the standard imaplib, return values are fully parsed into sensible Python types.
    • Exception Handling: Errors raise exceptions instead of requiring manual return value checking.
    • UID Support: You can initialize with use_uid=True to work with unique identifiers instead of sequence numbers.
    from imapclient import IMAPClient
    
    # Connect to the server
    server = IMAPClient('imap.mailserver.com', use_uid=True)
    server.login('someuser', 'somepassword')
    
    # Select a folder
    select_info = server.select_folder('INBOX')
    print('%d messages in INBOX' % select_info[b'EXISTS'])
    
    # Search for messages
    messages = server.search(['FROM', 'best-friend@domain.com'])
    
    # Fetch message data (e.g., ENVELOPE)
    for msgid, data in server.fetch(messages, ['ENVELOPE']).items():
        envelope = data[b'ENVELOPE']
        print('ID #%d: "%s" received %s' % (msgid, envelope.subject.decode(), envelope.date))
    
    # Clean up
    server.logout()
  9. Use the IMAPClient interactive console

    master

    To explore the IMAPClient API and test commands without writing a full script, you can use the interactive console. It uses IPython if installed, otherwise it falls back to the standard library's code.interact().

    Run the following command:

    python -m imapclient.interact ...
  10. Start an interactive IMAP session

    master

    You can use the imapclient.interact module to launch an interactive shell connected to an IMAP server. This is useful for testing commands and exploring server responses. If IPython is installed, it will be used as the shell; otherwise, the standard Python shell is used. Once connected, the IMAPClient instance is available via the variable c.

    # Start a session with host and user
    python -m imapclient.interact -H <host> -u <user>
    
    # Start a session using a configuration file
    python -m imapclient.interact -f <config file>