IMAPClient

3.1.0 · active · verified Sat Apr 11

IMAPClient is an easy-to-use, Pythonic, and complete IMAP client library. It provides a higher-level API over Python's built-in `imaplib` module, simplifying interaction with IMAP servers. The library is actively maintained, with its current version being 3.1.0, and receives regular updates.

Warnings

Install

Imports

Quickstart

This quickstart connects to an IMAP server, logs in using credentials from environment variables, selects the 'INBOX' folder, and fetches the subjects of the first few messages. It demonstrates basic connection, authentication, folder selection, and message fetching. Ensure `IMAP_HOST`, `IMAP_USERNAME`, and `IMAP_PASSWORD` environment variables are set.

import os
from imapclient import IMAPClient

# Environment variables for credentials
IMAP_HOST = os.environ.get('IMAP_HOST', 'imap.example.com')
IMAP_USERNAME = os.environ.get('IMAP_USERNAME', 'your_username')
IMAP_PASSWORD = os.environ.get('IMAP_PASSWORD', 'your_password')

try:
    # Connect to the IMAP server using a context manager for automatic logout
    with IMAPClient(IMAP_HOST, ssl=True) as client:
        client.login(IMAP_USERNAME, IMAP_PASSWORD)
        print(f"Successfully logged in to {IMAP_HOST} as {IMAP_USERNAME}")

        # Select the INBOX folder
        select_info = client.select_folder('INBOX')
        print(f"Selected INBOX: {select_info[b'EXISTS']} messages")

        # Search for all messages
        messages = client.search(['ALL'])
        print(f"Found {len(messages)} messages.")

        if messages:
            # Fetch subjects of the first 5 messages (or fewer if not enough)
            fetch_uids = messages[:5]
            response = client.fetch(fetch_uids, ['BODY.PEEK[HEADER.FIELDS (SUBJECT)]'])

            print("\n--- Subjects of first messages ---")
            for uid, data in response.items():
                subject_bytes = data[b'BODY[HEADER.FIELDS (SUBJECT)]']
                try:
                    # Decode subject, handling potential encoding issues
                    subject = subject_bytes.decode('utf-8', errors='ignore').strip()
                    print(f"UID {uid}: {subject}")
                except UnicodeDecodeError:
                    print(f"UID {uid}: Subject decoding failed")
        else:
            print("No messages in INBOX.")

except Exception as e:
    print(f"An error occurred: {e}")

view raw JSON →