imaplib2

raw JSON →
3.6 verified Fri May 01 auth: no python

imaplib2 is a threaded Python IMAP4 client library, compatible with Python 3.6+. Version 3.6 is the latest stable release. It is maintained by the Jazzband community and provides an alternative to the standard library's imaplib, with threading support and improved performance.

pip install imaplib2
error AttributeError: module 'imaplib2' has no attribute 'IMAP4'
cause Import statement is `import imaplib2` but the class is in submodules.
fix
Use from imaplib2 import IMAP4 or import imaplib2; imaplib2.IMAP4 (imaplib2 exposes IMAP4 as alias).
error imaplib2.IMAP4.error: command SEARCH illegal in state NONAUTH
cause Trying to execute commands before login or after logout.
fix
Ensure you call login() or authenticate() before any mailbox commands.
error imaplib2.IMAP4.abort: connection closed unexpectedly
cause Server timeout or network issue; library raises abort on connection loss.
fix
Implement reconnect logic. Use try/except and re-instantiate connection.
deprecated imaplib2 3.x drops support for SSL/TLS context parameters like `keyfile` and `certfile`. Use `ssl_context` instead.
fix Replace `keyfile` and `certfile` arguments with `ssl.SSLContext` object passed to `IMAP4_SSL`.
breaking In version 3.x, the `IMAP4` class no longer supports direct SSL without using `IMAP4_SSL`. Plain `IMAP4` is for non-SSL connections only.
fix Use `IMAP4_SSL` for SSL connections, not `IMAP4`.
gotcha The library is thread-safe but not fork-safe. Using `os.fork()` after creating an IMAP connection may lead to undefined behavior.
fix Avoid forking after establishing an IMAP session. Reconnect in child processes if needed.

Connect to an IMAP server, login, select inbox, and search for all messages.

import os
from imaplib2 import IMAP4

with IMAP4('imap.example.com') as M:
    M.login(os.environ['USER'], os.environ['PASS'])
    M.select()
    typ, data = M.search(None, 'ALL')
    print(data)