On this page
imaplib
Prev: idlelib | Up: stdlib_module | Next: importlib
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — imaplib
Tags: #public #python3 #stdlib
Import
import imaplib
Overview
Low-level IMAP4 client (IMAP4, IMAP4_SSL) for connecting to mail servers, selecting folders, searching messages, and fetching raw RFC 822 email bytes. Use imaplib paired with email when automating inbox polling or mailbox archival without third-party dependencies.
Quick Start
import email
from email import policy
import imaplib
def fetch_latest_subject(host: str, user: str, credential: str) -> str | None:
with imaplib.IMAP4_SSL(host, 993, timeout=30) as client:
client.login(user, credential)
client.select("INBOX", readonly=True)
status, data = client.uid("search", None, "ALL")
uids = data[0].split()
if status != "OK" or not uids:
return None
_, msg_data = client.uid("fetch", uids[-1], "(RFC822)")
raw = msg_data[0][1]
msg = email.message_from_bytes(raw, policy=policy.default)
return msg["Subject"]
Implementation Walkthrough
1. Prefer UIDs Over Sequence Numbers
IMAP message sequence numbers shift whenever messages are expunged, whereas UIDs stay stable within a folder (UIDVALIDITY):
import imaplib
def search_unseen_uids(client: imaplib.IMAP4_SSL) -> list[bytes]:
client.select("INBOX", readonly=True)
status, data = client.uid("search", None, "UNSEEN")
if status != "OK" or not data or not data[0]:
return []
return data[0].split()
Gotchas & Boundaries
- Always use
IMAP4_SSL(port 993) orstarttls(): PlainIMAP4sends credentials in cleartext; pass an explicitssl_context=ssl.create_default_context()when tightening TLS verification. - Raw protocol responses:
fetch()returns nested tuples ofbytesand server literals, not parsed objects—always pass raw message bytes toemail.message_from_bytes(..., policy=policy.default). - No automatic OAuth2 helper: Modern providers (Gmail, Microsoft 365) require app passwords or
authenticate("XOAUTH2", ...)with an OAuth2 bearer token. - Set a socket timeout: Pass
timeout=30toIMAP4_SSL(...)so stalled network calls don't hang indefinitely.
Common Functions
- imaplib.Int2AP() —
Int2AP(num)— Convert integer to A-P string representation. - imaplib.Internaldate2tuple() —
Internaldate2tuple(resp)— Parse an IMAP4 INTERNALDATE string. - imaplib.ParseFlags() —
ParseFlags(resp)— Convert IMAP4 flags response to python tuple. - imaplib.Time2Internaldate() —
Time2Internaldate(date_time)— Convert date_time to IMAP4 INTERNALDATE representation.
Classes & Objects
- imaplib.IMAP4 — IMAP4 client class. (Methods:
.abort(),.append(),.authenticate(),.capability(),.check(),.close()) - imaplib.IMAP4_SSL — IMAP4 client class over SSL connection Instantiate with: IMAP4_SSL([host[, port[, ssl_context[, timeout=None]]]]) host - host's name (default: localhost); (Methods:
.abort(),.append(),.authenticate(),.capability(),.check(),.close()) - imaplib.IMAP4_stream — IMAP4 client class over a stream Instantiate with: IMAP4_stream(command) "command" - a string that can be passed to subprocess.Popen() (Methods:
.abort(),.append(),.authenticate(),.capability(),.check(),.close())
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/idlelib
- tuts/python3/stdlib_module/imaplib/IMAP4
- tuts/python3/stdlib_module/imaplib/IMAP4_SSL
- tuts/python3/stdlib_module/imaplib/IMAP4_stream
- tuts/python3/stdlib_module/imaplib/Int2AP
- tuts/python3/stdlib_module/imaplib/Internaldate2tuple
- tuts/python3/stdlib_module/imaplib/ParseFlags
- tuts/python3/stdlib_module/imaplib/Time2Internaldate
- tuts/python3/stdlib_module/importlib
- tuts/python3/stdlib_module/stdlib_module
Related notes
- tuts/python3/stdlib_module/idlelib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/imaplib/IMAP4 Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/imaplib/IMAP4_SSL Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/imaplib/IMAP4_stream Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/imaplib/Int2AP Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/imaplib/Internaldate2tuple Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/imaplib/ParseFlags Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/imaplib/Time2Internaldate Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/importlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib