IMAPClient
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
- breaking Version 3.0.0 removed official support for Python 2.x. Applications targeting Python 2 must remain on `imapclient < 3.0.0`.
- breaking Version 3.0.0 also removed support for Python 3.4, 3.5, and 3.6. The current officially supported Python versions are 3.8 through 3.13.
- gotcha Users running Python 3.14+ might experience compatibility issues with `IMAP4_TLS` if using `imapclient` versions older than 3.1.0.
- gotcha Since version 1.0, IMAPClient enables strict TLS certificate verification by default. Connections to servers with self-signed or invalid certificates may fail.
Install
-
pip install imapclient
Imports
- IMAPClient
from imapclient import IMAPClient
Quickstart
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}")