Explaining IMAP IDLE with imaplib and example
The user wants to use Python's standard imaplib to send the IMAP IDLE command and block until the server pushes a new email notification. Since imaplib doesn't provide a high-level idle method, the approach involves sending the IDLE command manually, then blocking on the socket until an untagged response like "* n EXISTS" arrives indicating new mail. After that, the client sends "DONE" to end IDLE, fetches the new messages, and re-enters IDLE. Using select on the socket combined with imaplib's internal _get_line() method lets us implement this blocking behavior. The answer includes a concise, practical example demonstrating this pattern, while cautioning this uses imaplib's private APIs and suggesting libraries like imapclient for production use.
IDLE (RFC 2177) keeps the connection open and allows the server to send you untagged updates such as * 23 EXISTS when a new message is delivered. The sequence is:
- Login and
SELECT the mailbox.
- Send the
IDLE command and wait for the server’s + idling continuation.
- Block on the socket until you see an untagged response.
- Send
DONE to terminate the idle, read the tagged OK, then issue a normal SEARCH/FETCH to get the new message.
- Go back to step 2.
imaplib doesn’t expose a high–level idle API, so you have to use a couple of its “private” helpers to drive the protocol yourself:
import imaplib
import select
HOST = 'imap.example.com'
USER = 'user@example.com'
PASS = 'secret'
def start_idle(conn):
tag = conn._new_tag()
conn.send(f'{tag} IDLE\r\n'.encode('ascii'))
# Expect a "+ idling" continuation from the server
if not conn._get_line().startswith(b'+'):
raise RuntimeError('IDLE not supported')
return tag
def end_idle(conn, tag):
conn.send(b'DONE\r\n')
# Read until we get the tagged completion for our IDLE
while True:
line = conn._get_line()
if line.startswith((tag + ' OK').encode('ascii')):
break
with imaplib.IMAP4_SSL(HOST) as M:
M.login(USER, PASS)
M.select('INBOX')
while True:
tag = start_idle(M)
# Block until the socket becomes readable
rlist, _, _ = select.select([M.sock], [], [])
if rlist:
# Read the untagged response
resp = M._get_line()
print('Server said:', resp)
if resp.startswith(b'*') and b'EXISTS' in resp:
# New mail arrived, stop idling and fetch it
end_idle(M, tag)
typ, data = M.search(None, 'UNSEEN')
for num in data[0].split():
typ, msg_data = M.fetch(num, '(RFC822)')
# process msg_data here…
continue # re‑enter IDLE in next loop
# if needed, add a timeout and re‑enter IDLE on timeout
This code will block in select until the server sends something. When a * … EXISTS arrives, it breaks out of IDLE with DONE, fetches unseen messages immediately, and then loops back into IDLE. For production code consider using imapclient or imaplib2, which have an idle() method and callbacks.