On this page
  1. poplib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Peeking at Headers Without Downloading Full Bodies
  7. Gotchas & Boundaries
  8. Classes & Objects

poplib

Prev: plistlib | Up: stdlib_module | Next: posix
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — poplib
Tags: #public #python3 #stdlib


Import

import poplib

Overview

Low-level POP3 client (POP3, POP3_SSL) for retrieving and deleting messages from a POP3 mail drop. Use poplib only when integrating with legacy mail servers or simple single-inbox queues that don't offer IMAP or an HTTP API.

Quick Start

import email
from email import policy
import poplib

def read_pop3_inbox(host: str, user: str, credential: str) -> list[str]:
    subjects: list[str] = []
    conn = poplib.POP3_SSL(host, 995, timeout=30)
    try:
        conn.user(user)
        conn.pass_(credential)
        count, _size = conn.stat()
        for num in range(1, count + 1):
            _resp, lines, _octets = conn.retr(num)
            msg = email.message_from_bytes(b"\r\n".join(lines), policy=policy.default)
            subjects.append(msg["Subject"] or "")
    finally:
        conn.quit()
    return subjects

Implementation Walkthrough

1. Peeking at Headers Without Downloading Full Bodies

top(which, howmuch) fetches message headers plus howmuch body lines—useful for filtering large attachments before calling retr():

import poplib

def peek_headers(conn: poplib.POP3_SSL, msg_num: int) -> bytes:
    _resp, lines, _octets = conn.top(msg_num, 0)
    return b"\r\n".join(lines)

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes