Simple, reliable IMAP interface for Envoy using Python's standard imaplib. Credentials are read from ~/.netrc using the netrc module.
imap_client.py
Add an entry to ~/.netrc:
machine imap.example.com
login user@example.com
password yourpassword
The file must have restricted permissions: chmod 600 ~/.netrc
from imap_client import IMAPClient
with IMAPClient('imap.example.com') as client:
client.select_folder('INBOX')
messages = client.search('UNSEEN')
for msg_id in messages:
data = client.fetch(msg_id)
# process message...
python imap_client.py imap.example.com INBOX
list_folders() — List all folders in the mailbox
select_folder(folder) — Select a folder for operations
search(criteria) — Search for messages. Examples: 'ALL', 'UNSEEN', 'FROM "sender@example.com"'
fetch(message_id) — Fetch full message by ID
move_message(message_id, destination_folder) — Move message to another folder
delete_message(message_id) — Mark message for deletion
expunge() — Permanently delete marked messages
Uses standard library imaplib — No external dependencies
Credentials from .netrc — Standard Unix approach, secure
Context manager support — Ensures cleanup on errors
Exceptions propagate — Caller decides error handling strategy
Works as both script and library — Follows main() pattern from PROGRAMMING_RULES
from imap_client import IMAPClient
with IMAPClient('mail.critchley.biz') as client:
# Select inbox
status, count = client.select_folder('INBOX')
print(f"Messages in INBOX: {count}")
# Find unread messages
unread = client.search('UNSEEN')
for msg_id in unread:
# Fetch and process
message_data = client.fetch(msg_id)
# Move to Active folder after processing
client.move_message(msg_id, 'Active')
# Commit deletions
client.expunge()