On this page
  1. imaplib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Prefer UIDs Over Sequence Numbers
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

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

Common Functions

Classes & Objects

Linked from

Related notes