问题
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.
回答1:
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)
回答2:
I know you have accepted an answer, but I think a better approach than reconnecting is to issue the NOOP command.
回答3:
Drop the time.sleep(60)
and use idle() from this version of imaplib instead. A 29-minute timeout is fine. You may have to use a shorter timeout if you have a broken NAT gateway in front of your network.
The IMAP command IDLE instructs the server to let the client know as soon as anything has changed. So you run IDLE, then when the server says something, you rerun your search. You should be able to react to changes within a second or two that way.
回答4:
You can issue NOOP command in the while loop or IDLE for update the IMAP session.
来源:https://stackoverflow.com/questions/28190765/python-imaplib-get-new-gmail-mails-without-reconnect