Skip to main content

Python asyncio IMAP4rev1 client library

Project description


Build status

This library is inspired by imaplib and imaplib2 from Piers Lauder, Nicolas Sebrecht, Sebastian Spaeth. Some utilities functions are taken from imaplib/imaplib2 thanks to them.

The aim is to port the imaplib with asyncio, to benefit from the sleep or treat model.

It runs with python 3.6, 3.7, 3.8, 3.9.


import asyncio
from aioimaplib import aioimaplib

async def check_mailbox(host, user, password):
    imap_client = aioimaplib.IMAP4_SSL(host=host)
    await imap_client.wait_hello_from_server()

    await imap_client.login(user, password)

    res, data = await
    print('there is %s messages INBOX' % data[0])

    await imap_client.logout()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(check_mailbox('my.imap.server', 'user', 'pass'))

Beware that the IMAP4.close() function is an IMAP function that is closing the selected mailbox, thus passing from SELECTED state to AUTH state. It does not close the TCP connection. The way to close TCP connection properly is to logout.

IDLE command

The RFC2177 is implemented, to be able to wait for new mail messages without using CPU. The responses are pushed in an async queue, and it is possible to read them in real time. To leave the IDLE mode, it is necessary to send a “DONE” command to the server.

async def wait_for_new_message(host, user, password):
    imap_client = aioimaplib.IMAP4_SSL(host=host)
    await imap_client.wait_hello_from_server()

    await imap_client.login(user, password)

    idle = await imap_client.idle_start(timeout=10)
    while imap_client.has_pending_idle():
        msg = await imap_client.wait_server_push()
        if msg == STOP_WAIT_SERVER_PUSH:
            await asyncio.wait_for(idle, 1)

    await imap_client.logout()

if __name__ == '__main__':
        loop = asyncio.get_event_loop()
        loop.run_until_complete(wait_for_new_message('my.imap.server', 'user', 'pass'))

Or in a more event based style (the IDLE command is closed at each message from server):

async def idle_loop(host, user, password):
   imap_client = aioimaplib.IMAP4_SSL(host=host, timeout=30)
   await imap_client.wait_hello_from_server()

   await imap_client.login(user, password)

   while True:
      print((await imap_client.uid('fetch', '1:*', 'FLAGS')))

      idle = await imap_client.idle_start(timeout=60)
      print((await imap_client.wait_server_push()))

      await asyncio.wait_for(idle, 30)


The IMAP4ClientProtocol class is not thread safe, it uses asyncio.Event and asyncio.Condition that are not thread safe, and state change for pending commands is not locked.

It is possible to use threads but each IMAP4ClientProtocol instance should run in the same thread:


Each color rectangle is an IMAP4ClientProtocol instance piece of code executed by the thread asyncio loop until it reaches a yield, waiting on I/O.

For example, it is possible to launch 4 mono-threaded mail-fetcher processes on a 4 cores server with supervisor, and use a distribution function like len(email) % (process_num) or whatever to share equally a mail account list between the 4 processes.

IMAP command concurrency

IMAP protocol allows to run some commands in parallel. Four rules are implemented to ensure responses consistency:

  1. if a sync command is running, the following requests (sync or async) must wait

  2. if an async command is running, same async commands (or with the same untagged response type) must wait

  3. async commands can be executed in parallel

  4. sync command must wait pending async commands to finish


As said in the logging howto the logger is defined with

logger = logging.getLogger(__name__)

Where name is ‘aioimaplib.aioimaplib’. You can set the logger parameters, either by python API

aioimaplib_logger = logging.getLogger('aioimaplib.aioimaplib')
sh = logging.StreamHandler()
sh.setFormatter(logging.Formatter("%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s"))

Or loading config file (for example with logging.config.dictConfig(yaml.load(file))) with this piece of yaml file

    level: DEBUG
    handlers: [syslog]
    propagate: no

Tested with

  • dovecot 2.2.13 on debian Jessie

  • gmail with imap and SSL

  • outlook with SSL

  • yahoo with SSL

  • with SSL

  • with SSL

  • with SSL


Developers are welcome! If you want to improve it, fix bugs, test it with other IMAP servers, give feedback, thank you for it.

To develop, just run

virtualenv --python=python3.4 venv
source venv/bin/activate
python develop
pip install -r dev-requirements.txt

To add an imaplib or imaplib2 command you can :

  • add the function to the testing imapserver with a new imaplib or imaplib2 server test, i.e. or respectively;

  • then add the function to the aioimaplib doing almost the same test than above but the async way in

Not unit tested



  • 23/25 IMAP4rev1 commands are implemented from the main rfc3501. ‘STARTTLS’ and ‘AUTHENTICATE’ are still missing.

  • ‘COMPRESS’ from rfc4978


  • ‘GETQUOTA’: ‘GETQUOTAROOT’: ‘SETQUOTA’ from quota rfc2087

  • ‘SORT’ and ‘THREAD’ from the rfc5256

  • ‘ID’ from the rfc2971

  • ‘NAMESPACE’ from rfc2342

  • ‘CATENATE’ from rfc4469

  • tests with other servers

If it goes wrong

Sometimes you break things and you don’t understand what’s going on (I always do). For this library I have two related tools:

  • ngrep on the imap test port: sudo ngrep -d lo port 12345

  • activate debug logs changing INFO to DEBUG at the top of the mock server and the aioimaplib



After 5 years and 420 usages let’s switch to 1.0.0.

  • [aiolib] adds python 3.10 (but python 3.10 is failing on downloading interpretor)

  • [aiolib] adds getquotaroot command


Please note that this release changes the API : response lines are now all of bytes type (and not in string).

  • [aiolib] compatible with python 3.9

  • [aiolib] avoid having distinct types (str/bytes) in response lines


  • [aiolib] adds type hints

  • [aiolib] use async/await syntax (remove support for python 3.4)

  • [aiolib] fixes issue #30 on idle race condition

  • [aiolib] fixes the allowed version


  • [aiolib] fix the fix python 3.7 don’t use the 7.17


  • [aiolib] fix loading issue when importing aioimaplib with python 3.7


merge from darkrain42

  • [aiolib] fix interaction between idle loop and server keepalive

  • [aiolib] fix cert verification on debian buster

  • [test] fix imapserver literal handling on Python 3.6.5+

  • [test] tests: Replace calls to asyncio.async with asyncio.ensure_future


  • [aiolib] replace ‘async’ by is_async for python 3.7 cf #42

  • [aiolib] Add ID command

  • [aiolib] Add NAMESPACE command


  • [fix] when there is ::1 as localhost in /etc/hosts in a docker container

  • [test] tests with SSL

  • [aiolib] quote password properly in IMAP dialog


  • [aiolib] adds a connection lost callback

  • [test] imapserver : added APPENDUID response for APPEND cmd

  • [test][fix] imapserver append should add to the connected user mb

  • [test] imapserver : more accurate building of message headers (using python email module)


  • [aiolib] fix issue #24

  • [aiolib] fix issue #27


  • [aiolib] adds rfc6851 move


  • [aiolib] adds IMAP4.has_capability function


  • [aiolib] adds uncomplete fetch command with uncomplete line

  • [aiolib] adds uncomplete fetch command BODY without literal

  • [aiolib] adds rfc4315 uidplus : expunge with uids

  • [test] handles uidset better in imap server

  • [test] refactor testing IMAP4ClientProtocol.data_received instead of _handle_responses


  • [aiolib] idle : added an idle_waiter for an event based idle loop


  • [aiolib] do not filter exists line for examine command

  • [aiolib] idle : wait for the end of data frame before pushing into the queue

  • [test] imapserver enhancements : accepts sequence sets/returns UID when fetch by uid


  • [aiolib] idle : added loop methods


  • [aiolib][fix] it’s up to the user to send idle DONE


  • [aiolib] timeout for idle of 29 minutes + timeout of wait_server_push doesn’t raise TimeoutException


  • [aiolib] added timeout for wait_server_push of 29 minutes

  • [aiolib] Remove imap’s Continuation from server when connection is idled. Provide imapserver.wait_state to wait for idle in tests

  • [test][refactor] Replace WithIMapServer inheritance by mixin combinations between ClockTestCase/TestCase and WithIMapServer

  • [test] Allow to send a html email

  • [fix] handling untagged responses with noop async command


  • [fix] bug when incomplete literal occured before a tagged status line

  • [tests] imapserver search with uid range

  • [tests] better fetch request handling

  • [log] Limit partials’ log to 100 characters

  • [build] Add tests’ requires in


  • [refactor] adding incomplete line before calling _handle_responses


  • [fix] generalization of literal treatment

  • do not filter exists line for ‘select’ command (breaks the API). To retrieve unread mails with select, use

    aioimaplib.extract_exists((yield from instead of ‘yield from[0]’


  • [fix] added ‘$’ and ‘;’ for fetch message with litteral regexp


  • [fix] issue #17 “Error fetch uid param”




  • tests : [revert] add_charset to much intrusive when running a test suite


  • tests : body text was not base64 encoded even if the header said so



  • tests : added better encoding handling and message building in Mail.create


  • tests : added message_id as Mail.create parameter for testing


  • tests : extract Mail.create_binary for convenience


  • fix : trailing whitespace bug causing “BAD Could not parse command” using gmail/IDLE

  • fix : stop adding a space for the prefix ‘UID ‘ -> ‘UID’


  • fix : issue #12 Not properly buffering newlines for incomplete lines

  • fix : imapserver with status of an inexistant mailbox

  • fix : remove offset problem with strip() modifying length of read data

  • fix : remove ‘unknown data received’ logs if line is empty


  • remove hard coded logging config

  • doc : added logging settings


  • added rfc5032 ‘within’ function to server and tests for aiolib (it is only YOUNGER/OLDER arguments)


  • pushing continuation in the queue when idled


  • added a stop waiting server push function to interupt yield from queue.get


  • server send still here every IDLE_STILL_HERE_PERIOD_SECONDS to client when idle

  • fix when server was lauched with main, loop is already running


  • fix doc

  • fix imapserver main (needs a asyncio.loop.run_forever())


  • fix issues with coroutines in uid command

  • documentation



  • refactor: treating response as we read the imap server responses for a better reading

  • doc

  • removing tests from package

  • publish on pypi

  • added coverall


  • fix aioimaplib bug when receiving chunked fetch data

  • do not abort when receiving unsollicited data from server


  • build CI environment

  • license GPL v3.0


  • added APPEND command

  • fix usernames can have ‘@’ for mockimapserver

  • server can handle SEARCH with CHARSET opt parameter (but ignores it)


  • added 11 new imap commands

  • added imap command synchronizing

  • refactor

  • documentation


  • init project with mockimapserver

  • project files

  • 11 imap commands

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aioimaplib-hakiergrzonzo-1.0.1.tar.gz (390.5 kB view hashes)

Uploaded source

Built Distributions

aioimaplib_hakiergrzonzo-1.0.1-py3.10.egg (16.3 kB view hashes)

Uploaded 1 0 1

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Huawei Huawei PSF Sponsor Microsoft Microsoft PSF Sponsor NVIDIA NVIDIA PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page