Search code examples
pythonemailgmailimapgmail-imap

Python Imaplib: Get new gmail mails without reconnect


I'm writing a python script that regularly checks for new email matching a certain search. However it never shows new emails without reconnecting.

mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login(user,passwd)
mail.select("inbox")
while True:
    result, idData = mail.uid('search', query, "ALL")
    processIDs(idData)
    time.sleep(60)

The search finds all emails that match my query at login time, but it never finds emails that arrive while it's running. As soon as I stop the script and restart it, all emails instantly show up.

If googled and looked through the imaplib docs, but couldn't find anything useful.

How can I get the new emails to show without reconnecting to the imap server?

Edit: The reason I want to avoid reconnecting is because of gmail rate limits.


Solution

  • Well this is a kind of hit and trial approach and finally we get a solution, not optimal though, The hack is to reconnect again every time after the script wakes up from the sleep, to fetch the inbox from start, This can be easily done by refreshing the page(like we reload in the normal browser), So it may look like this :

    mail = imaplib.IMAP4_SSL('imap.gmail.com')
    mail.login(user,passwd)
    while True:
        mail.select("inbox")
        result, idData = mail.uid('search', query, "ALL")
        processIDs(idData)
        time.sleep(60)