Main function refactored and connection failure exception handling added
[imap-fix-internaldate] / mail_iterator.py
index e4da7d4..a17ab6c 100644 (file)
@@ -31,21 +31,28 @@ class MailIterator:
     mail_con = None
     # list of tuples (uidvalidity, mailboxname) for the retrieved mailboxes
     mailboxes = None
+    # logged in status
+    logged_in = None
 
     def __init__(self, server, username, password):
         """Creates a connection and a user session."""
-        self.mail_con = imaplib.IMAP4_SSL(server)
-        result, data = self.mail_con.login(username, password)
-        if(result!="OK"):
-            raise UserWarning("Could not log in as user " + username + ". " + data)
+        try:
+            self.mail_con = imaplib.IMAP4_SSL(server)
+            self.mail_con.login(username, password)
+            logging.info("Logged in as %s.", username)
+        except:
+            self.logged_in = False
+            raise UserWarning("Could not log in as user " + username + ".")
+        self.logged_in = True
         result, self.mailboxes = self.mail_con.list()
         if(result!="OK"):
             raise UserWarning("Could not retrieve mailboxes for user " + username + ".")
 
     def __del__(self):
         """Closes the connection and the user session."""
-        self.mail_con.close()
-        self.mail_con.logout()
+        if(self.logged_in):
+            self.mail_con.close()
+            self.mail_con.logout()
 
     def __iter__(self):
         """Iterates through all mailboxes, returns (uidval,name)."""