Skip to main content

About

Build status https://coveralls.io/repos/github/bamthomas/aioimaplib/badge.svg

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.

Thank you to all contributors for your time and interest :pray: :point_right:

The aim is to port the imaplib with asyncio, to benefit from the sleep or treat model. It has no dependencies for runtime (the core library).

It is tested against python 3.9, 3.10, 3.11 matrix. But the library itself could run with other python versions.

Example

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 imap_client.select()
    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)
    await imap_client.select()

    idle = await imap_client.idle_start(timeout=10)
    while imap_client.has_pending_idle():
        msg = await imap_client.wait_server_push()
        print(msg)
        if msg == STOP_WAIT_SERVER_PUSH:
            imap_client.idle_done()
            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)
   await imap_client.select()

   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()))

      imap_client.idle_done()
      await asyncio.wait_for(idle, 30)

Threading

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:

images/thread_imap_protocol.png

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

Logging

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.setLevel(logging.DEBUG)
sh.setFormatter(logging.Formatter("%(asctime)s %(levelname)s [%(module)s:%(lineno)d] %(message)s"))
aioimaplib_logger.addHandler(sh)

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

loggers:
...
  aioimaplib.aioimaplib:
    level: DEBUG
    handlers: [syslog]
    propagate: no
...

Authentication with OAuth2

Starting with the 01/01/23 Microsoft Outlook can only be accessed with OAuth2. You need to register you client to be used with oauth. Find more :https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth:here.

This might be also used with Google Mail, but it is not tested for it.

Tested with

  • dovecot 2.2.13 on debian Jessie

  • gmail with imap and SSL

  • outlook with SSL

  • yahoo with SSL

  • free.fr with SSL

  • orange.fr with SSL

  • mailden.net with SSL

Develop

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

We use poetry for building the library. Just run

poetry install
poetry run pytest

# or you can create a poetry shell
poetry install
poetry shell
pytest

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. test_imapserver_imaplib.py or test_imapserver_imaplib2.py respectively;

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

Not unit tested

  • PREAUTH

TODO

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

  • ‘COMPRESS’ from rfc4978

  • ‘SETACL’ ‘DELETEACL’ ‘GETACL’ ‘MYRIGHTS’ ‘LISTRIGHTS’ from ACL rfc4314

  • ‘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

Metadata

Release files for aioimaplib 2.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aioimaplib 2.0.1
File Size Uploaded
aioimaplib-2.0.1.tar.gz 35.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for aioimaplib 2.0.1
File Interpreter ABI Platform
aioimaplib-2.0.1-py3-none-any.whl Python 3 none any Details

Total release size: 70.3 kB

Release files / aioimaplib-2.0.1.tar.gz

Download URL aioimaplib-2.0.1.tar.gz
Size 35.6 kB
Tags Source
SHA-256 checksum
How to use checksums
5a494c3b75f220977048f5eb2c7ba9c0570a3148aaf38bee844e37e4d7af8648
BLAKE2b-256 checksum
How to use checksums
eedaa454c47fb8522e607425e15bf1f49ccfdb3d75f4071f40b63ebd49573495
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.7.1 CPython/3.10.12 Linux/6.8.0-51-generic

Release files / aioimaplib-2.0.1-py3-none-any.whl

Download URL aioimaplib-2.0.1-py3-none-any.whl
Size 34.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
727e00c35cf25106bd34611dddd6e2ddf91a5f1a7e72d9269f3ce62486b31e14
BLAKE2b-256 checksum
How to use checksums
135248aaa287fb3c4c995edcb602370b10d182dc5c48371df7cb3a404356733f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.7.1 CPython/3.10.12 Linux/6.8.0-51-generic

Release history Release notifications | RSS feed

This release

2.0.1 This release

2 release files

2.0.0

2 release files

1.2.0

2 release files

1.1.0

1 release file

1.0.1

3 release files

1.0.0

3 release files

0.9.0

3 release files

0.8.0

3 release files

0.7.18

3 release files

0.7.16

3 release files

0.7.15

3 release files

0.7.11

3 release files

0.7.10

3 release files

0.7.9

3 release files

0.7.8

3 release files

0.7.7

3 release files

0.7.6

3 release files

0.7.5

3 release files

0.7.4

3 release files

0.7.3

3 release files

0.7.2

3 release files

0.7.1

3 release files

0.7.0

3 release files

0.6.2

3 release files

0.6.1

3 release files

0.6.0

3 release files

0.5.20

3 release files

0.5.14

2 release files

0.5.13

2 release files

0.5.12

2 release files

0.5.11

3 release files

0.5.9

3 release files

0.5.8

3 release files

0.5.7

3 release files

0.5.6

3 release files

0.5.5

3 release files

0.5.4

3 release files

0.5.3

3 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page