Debian Codegraph @

example/imap_fetch.py

raw
1 import re
2 from asyncio import run, wait_for
3 from collections import namedtuple
4 from email.message import Message
5 from email.parser import BytesHeaderParser, BytesParser
6 from typing import Collection
7
8 import aioimaplib
9
10 ID_HEADER_SET = {'Content-Type', 'From', 'To', 'Cc', 'Bcc', 'Date', 'Subject',
11 'Message-ID', 'In-Reply-To', 'References'}
12 FETCH_MESSAGE_DATA_UID = re.compile(rb'.*UID (?P<uid>\d+).*')
13 FETCH_MESSAGE_DATA_SEQNUM = re.compile(rb'(?P<seqnum>\d+) FETCH.*')
14 FETCH_MESSAGE_DATA_FLAGS = re.compile(rb'.*FLAGS \((?P<flags>.*?)\).*')
15 MessageAttributes = namedtuple('MessageAttributes', 'uid flags sequence_number')
16
17
18 async def fetch_messages_headers(imap_client: aioimaplib.IMAP4_SSL, max_uid: int) -> int:
19 response = await imap_client.uid('fetch', '%d:*' % (max_uid + 1),
20 '(UID FLAGS BODY.PEEK[HEADER.FIELDS (%s)])' % ' '.join(ID_HEADER_SET))
21 new_max_uid = max_uid
22 if response.result == 'OK':
23 for i in range(0, len(response.lines) - 1, 3):
24 fetch_command_without_literal = b'%s %s' % (response.lines[i], response.lines[i + 2])
25
26 uid = int(FETCH_MESSAGE_DATA_UID.match(fetch_command_without_literal).group('uid'))
27 flags = FETCH_MESSAGE_DATA_FLAGS.match(fetch_command_without_literal).group('flags')
28 seqnum = FETCH_MESSAGE_DATA_SEQNUM.match(fetch_command_without_literal).group('seqnum')
29 # these attributes could be used for local state management
30 message_attrs = MessageAttributes(uid, flags, seqnum)
31 print(message_attrs)
32
33 # uid fetch always includes the UID of the last message in the mailbox
34 # cf https://tools.ietf.org/html/rfc3501#page-61
35 if uid > max_uid:
36 message_headers = BytesHeaderParser().parsebytes(response.lines[i + 1])
37 print(message_headers)
38 new_max_uid = uid
39 else:
40 print('error %s' % response)
41 return new_max_uid
42
43
44 async def fetch_message_body(imap_client: aioimaplib.IMAP4_SSL, uid: int) -> Message:
45 dwnld_resp = await imap_client.uid('fetch', str(uid), 'BODY.PEEK[]')
46 return BytesParser().parsebytes(dwnld_resp.lines[1])
47
48
49 def handle_server_push(push_messages: Collection[str]) -> None:
50 for msg in push_messages:
51 if msg.endswith(b'EXISTS'):
52 print('new message: %s' % msg) # could fetch only the message instead of max_uuid:* in the loop
53 elif msg.endswith(b'EXPUNGE'):
54 print('message removed: %s' % msg)
55 elif b'FETCH' in msg and b'\Seen' in msg:
56 print('message seen %s' % msg)
57 else:
58 print('unprocessed push message : %s' % msg)
59
60
61 async def imap_loop(host, user, password) -> None:
62 imap_client = aioimaplib.IMAP4_SSL(host=host, timeout=30)
63 await imap_client.wait_hello_from_server()
64
65 await imap_client.login(user, password)
66 await imap_client.select('INBOX')
67
68 persistent_max_uid = 1
69 while True:
70 persistent_max_uid = await fetch_messages_headers(imap_client, persistent_max_uid)
71 print('%s starting idle' % user)
72 idle_task = await imap_client.idle_start(timeout=60)
73 handle_server_push((await imap_client.wait_server_push()))
74 imap_client.idle_done()
75 await wait_for(idle_task, timeout=5)
76 print('%s ending idle' % user)
77
78
79 if __name__ == '__main__':
80 run(imap_loop('imap.server', 'account_id', 'password'))