IMAP Tools
imap-tools is a high-level Python library designed for working with email via the IMAP protocol. It provides a user-friendly interface for common email operations such as fetching, parsing, searching, moving, and deleting messages, as well as managing folders. The library is actively maintained, with frequent minor releases, and is currently at version 1.12.0.
Warnings
- breaking In v1.12.0, MailMessage.headers changed from a standard dictionary to a 'LazyHeaders' dict-like mapping. While often backward compatible, direct access to all headers might now trigger lazy loading, potentially affecting performance or requiring slight code adjustments if specific dict behaviors (e.g., direct `dict()` conversion) are relied upon.
- breaking In v1.11.0, `MailBoxTls` was renamed to `MailBoxStartTls`. Additionally, `MailBoxStartTls` now defaults to port 143 (standard IMAP) and explicitly raises a `ValueError` if port 993 (IMAPS) is specified, as 993 is intended for `MailBox` (IMAP-SSL/TLS) connections.
- breaking Starting with v1.9.0, support for Python versions 3.3, 3.4, 3.5, 3.6, and 3.7 was dropped. The library now requires Python 3.8 or newer.
- gotcha When performing bulk operations like `copy`, `move`, `flag`, or `delete` on a large number of messages, the IMAP command generated by the server might become too large, leading to server errors. The behavior and result types of `BaseMailBox.move` also changed in v1.10.0.
- gotcha Version 1.7.3 included a fix for `CVE-2023-27043` related to malformed addresses in `email.parseaddr()`. This might subtly alter how malformed email addresses are processed or rejected, potentially causing changes in behavior for applications handling emails with non-standard address formats.
Install
-
pip install imap-tools
Imports
- MailBox
from imap_tools import MailBox
- MailBoxStartTls
from imap_tools import MailBoxStartTls
- AND
from imap_tools import AND
Quickstart
import os
from imap_tools import MailBox, AND
IMAP_HOST = os.environ.get('IMAP_HOST', 'imap.mail.com')
IMAP_USER = os.environ.get('IMAP_USER', 'test@mail.com')
IMAP_PASS = os.environ.get('IMAP_PASS', 'your-password')
try:
with MailBox(IMAP_HOST).login(IMAP_USER, IMAP_PASS) as mailbox:
# Fetch all unseen emails from the INBOX and print their subject and sender
print(f"Connected to IMAP host: {IMAP_HOST}")
print("Fetching unseen emails...")
for msg in mailbox.fetch(criteria=AND(seen=False), mark_seen=False, limit=5):
print(f"From: {msg.from_}, Subject: {msg.subject}")
except Exception as e:
print(f"An error occurred: {e}")