aioimaplib - Async IMAP Client

2.0.1 · active · verified Thu Apr 16

aioimaplib is a Python asyncio IMAP4rev1 client library, providing asynchronous access to IMAP servers. It allows developers to interact with email servers, fetch messages, manage mailboxes, and more, using modern async/await syntax. The library is currently at version 2.0.1 and generally follows a release cadence tied to bug fixes and feature enhancements as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an IMAP server using TLS (IMAP4_SSL), log in, list available mailboxes, and count messages in the 'INBOX'. It uses `async with` for connection management and fetches credentials from environment variables.

import aioimaplib
import asyncio
import os

async def main():
    IMAP_HOST = os.environ.get('IMAP_HOST', 'imap.mail.com')
    IMAP_USER = os.environ.get('IMAP_USER', 'your_email@mail.com')
    IMAP_PASS = os.environ.get('IMAP_PASS', 'your_password')

    if not all([IMAP_HOST, IMAP_USER, IMAP_PASS]):
        print("Please set IMAP_HOST, IMAP_USER, and IMAP_PASS environment variables.")
        return

    try:
        async with aioimaplib.IMAP4_SSL(host=IMAP_HOST) as client:
            await client.wait_hello_from_server()
            await client.login(IMAP_USER, IMAP_PASS)
            print(f"Logged in as {IMAP_USER}")

            status, mailboxes = await client.list()
            if status == 'OK':
                print("Mailboxes:")
                for mb in mailboxes:
                    print(f"  {mb.decode('utf-8')}")
            else:
                print(f"Failed to list mailboxes: {status}")

            await client.select('INBOX')
            status, msg_ids = await client.search('ALL')
            if status == 'OK' and msg_ids[0]:
                print(f"INBOX contains {len(msg_ids[0].split())} messages.")
            elif status == 'OK':
                print("INBOX is empty.")
            else:
                print(f"Failed to search INBOX: {status}")

    except aioimaplib.exceptions.IMAP4Exception as e:
        print(f"IMAP error: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

if __name__ == '__main__':
    asyncio.run(main())

view raw JSON →