Search code examples
pythonimaplib

Unknown IMAP4 command: 'idle' When Accessing Inbox


I am trying to check for new emails in real time. I believe the code below should work but I get an "AttributeError: Unknown IMAP4 command: 'idle'" error. Can anyone see what the issue is?

import imaplib
import email

username = "[email protected]"
password = "xxxxx"

# Connect to the IMAP server
mail = imaplib.IMAP4_SSL('mail.xxxxx.com')

# Login to the server
mail.login(username, password)

# Select the INBOX folder
mail.select("INBOX")

# Start listening for new emails
mail.idle()

Solution

  • Updated answer:

    imaplib doesn't support IDLE. Github issue (from 2011!) for this is still open --> https://github.com/python/cpython/issues/55454

    It provides several solutions for this, so I'm not going to reinvent the wheel here (pun intended).


    Old answer

    I'm going to guess that your specific email server doesn't support the IDLE command.

    Quick recap here for the IDLE command, and note that this is an optional feature.

    You can check this using the code below (login to server not needed to check capabilities):

    import imaplib
    
    mail = imaplib.IMAP4_SSL('mail.xxxxx.com')
    print(mail.capabilities)
    

    This will output a tuple[str] which should look like this:

    ('IMAP4REV1', 'UNSELECT', 'IDLE', 'NAMESPACE', 'QUOTA', 'ID', 'XLIST', 'CHILDREN', 'X-GM-EXT-1', 'XYZZY', 'SASL-IR', 'AUTH=XOAUTH2', 'AUTH=PLAIN', 'AUTH=PLAIN-CLIENTTOKEN', 'AUTH=OAUTHBEARER')

    And note that in the response that I got (from GMail) includes the IDLE capability...