diff --git a/Mailnag/backends/imap.py b/Mailnag/backends/imap.py index 367808c..1733f02 100644 --- a/Mailnag/backends/imap.py +++ b/Mailnag/backends/imap.py @@ -72,7 +72,10 @@ class IMAPMailboxBackend(MailboxBackend): def list_messages(self): + self._ensure_open() + conn = self._conn + if len(self.folders) == 0: folder_list = [ 'INBOX' ] else: @@ -127,6 +130,8 @@ class IMAPMailboxBackend(MailboxBackend): def notify_next_change(self, callback=None, timeout=None): + self._ensure_open() + # register idle callback that is called whenever an idle event # arrives (new mail / mail deleted). # the callback is called after minutes at the latest. @@ -150,6 +155,11 @@ class IMAPMailboxBackend(MailboxBackend): def cancel_notifications(self): + # NOTE: Don't throw if the connection is closed. + # Analogous to close(). + # (Otherwise cleanup code like in Idler._idle() will fail) + # self._ensure_open() + try: if self._conn != None: # Exit possible active idle state. @@ -210,3 +220,8 @@ class IMAPMailboxBackend(MailboxBackend): folder = "INBOX" conn.select(folder, readonly = True) + + def _ensure_open(self): + if not self.is_open(): + raise InvalidOperationException("Account is not open") + diff --git a/Mailnag/backends/pop3.py b/Mailnag/backends/pop3.py index 8ac360e..38e37ce 100644 --- a/Mailnag/backends/pop3.py +++ b/Mailnag/backends/pop3.py @@ -67,20 +67,20 @@ class POP3MailboxBackend(MailboxBackend): conn = poplib.POP3(self.server, int(self.port)) # TODO : Use STARTTLS when Mailnag has been migrated to python 3 - # (analogous to get_connection in imap backend). + # (analogous to open() in imap backend). logging.warning("Using unencrypted connection for account '%s'" % self.name) conn.getwelcome() conn.user(self.user) conn.pass_(self.password) - - self._conn = conn except: try: if conn != None: conn.quit() except: pass raise # re-throw exception + + self._conn = conn def close(self): @@ -95,8 +95,11 @@ class POP3MailboxBackend(MailboxBackend): def list_messages(self): + self._ensure_open() + conn = self._conn folder = '' + # number of mails on the server mail_total = len(conn.list()[1]) for i in range(1, mail_total + 1): # for each mail @@ -130,3 +133,7 @@ class POP3MailboxBackend(MailboxBackend): def cancel_notifications(self): raise NotImplementedError("POP3 does not support notifications") + + def _ensure_open(self): + if not self.is_open(): + raise InvalidOperationException("Account is not open")