I am programming a python applet that watches the unread count of the email boxes for my workplace, and ran into an EOF error when I try to use any imaplib methods after the
I managed to integrate cxase's into a custom imap class that took care of all my problems. Here is the code for anyone reading this:
class IMAPConnection():
def __init__(self):
self.imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
def login (self):
# Login to Helpdesk Google Apps Email account using encryption
self.imap.login(base64.b64decode("username"), base64.b64decode("password"))
def logout (self):
self.imap.logout()
def getUnread (self):
# Check connection status OK
try:
uc0 = int(re.search("UNSEEN (\d+)", self.imap.status("INBOX", "(UNSEEN)")[1][0]).group(1))
uc1 = int(re.search("UNSEEN (\d+)", self.imap.status("A box 1", "(UNSEEN)")[1][0]).group(1))
uc2 = int(re.search("UNSEEN (\d+)", self.imap.status("A box 2", "(UNSEEN)")[1][0]).group(1))
except imap.abort:
# Reinstantiate connection and login
self.imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
self.login()
# Retry unread update block
uc0 = int(re.search("UNSEEN (\d+)", self.imap.status("INBOX", "(UNSEEN)")[1][0]).group(1))
uc1 = int(re.search("UNSEEN (\d+)", self.imap.status("A box 1", "(UNSEEN)")[1][0]).group(1))
uc2 = int(re.search("UNSEEN (\d+)", self.imap.status("A box 2", "(UNSEEN)")[1][0]).group(1))
# Is the Helpdesk Negative? Hell no it's not.
unreadCount = [(uc0-(uc1+uc2)),uc1,uc2]
if unreadCount[0] < 0:
unreadCount[0]=0
return unreadCount
You need to reconnect by re-initialize class, not just login, using
conn = imaplib.IMAP4_SSL("imap.gmail.com", 993)
A complete example:
while True:
imap = imaplib.IMAP4_SSL(SERVER)
r, d = imap.login(ACCOUNT, PASSWORD)
assert r == 'OK', 'login failed'
try:
# do things with imap
except imap.abort, e:
continue
imap.logout()
break