Ok just noticed some weird behavior in my code and just trying to get to the bottom of the problem. When using the imap library, and trying to check for mail, Do I have to log in each time to see if there is any new mail? For example
#get_mail function.
def get_mail():
conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.login(gmail_user_id,gmail_user_pass)
conn.select('inbox')
conn.search(None,'(Inbox)')
return something here
Instead could I do something like:
#create 'conn' as a global var
conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.login(gmail_user_id,gmail_user_pass)
conn.select('inbox')
#get_mail function
def get_mail():
conn.search(None,'(Inbox)')
return something here
The problem is that in the second snippet above, if a new mail has been sent AFTER the conn is created, it is not being fetched. So do I have to re-log in every single time the function is run?
Yes.
Normally, you wouldn’t have to login again – you would use
IDLEif the IMAP server supports it.IDLEsupport means you just have to poll for new messages by keeping a connection open (hence “idle”). See this link which describes how to listen for new messages in a loop.