diff --git a/django_mailbox/models.py b/django_mailbox/models.py index a27b5b25..d98ba1fd 100644 --- a/django_mailbox/models.py +++ b/django_mailbox/models.py @@ -470,15 +470,18 @@ def get_new_mail(self, condition=None): connection = self.get_connection() if not connection: return - for message in connection.get_message(condition): - msg = self.process_incoming_message(message) - if msg is not None: - yield msg - self.last_polling = now() - if django.VERSION >= (1, 5): # Django 1.5 introduces update_fields - self.save(update_fields=['last_polling']) - else: - self.save() + try: + for message in connection.get_message(condition): + msg = self.process_incoming_message(message) + if msg is not None: + yield msg + self.last_polling = now() + if django.VERSION >= (1, 5): # Django 1.5 introduces update_fields + self.save(update_fields=['last_polling']) + else: + self.save() + finally: + connection.close() @staticmethod def get_new_mail_all_mailboxes(args=None): diff --git a/django_mailbox/transports/base.py b/django_mailbox/transports/base.py index a90af9f7..57679f8a 100644 --- a/django_mailbox/transports/base.py +++ b/django_mailbox/transports/base.py @@ -9,3 +9,6 @@ def get_email_from_bytes(self, contents): message = email.message_from_bytes(contents) return message + + def close(self): + pass \ No newline at end of file diff --git a/django_mailbox/transports/imap.py b/django_mailbox/transports/imap.py index 2599adad..5b0d2dc8 100644 --- a/django_mailbox/transports/imap.py +++ b/django_mailbox/transports/imap.py @@ -6,13 +6,6 @@ from .base import EmailTransport, MessageParseError -# By default, imaplib will raise an exception if it encounters more -# than 10k bytes; sometimes users attempt to consume mailboxes that -# have a more, and modern computers are skookum-enough to handle just -# a *few* more messages without causing any sort of problem. -imaplib._MAXLINE = 1000000 - - logger = logging.getLogger(__name__) @@ -56,6 +49,14 @@ def connect(self, username, password): else: self.server.select() + def close(self): + try: + self.server.close() + self.server.logout() + except (imaplib.IMAP4.error, OSError) as e: + logger.warning(f'Failed to close IMAP connection, ignoring: {e}') + pass + def _get_all_message_ids(self): # Fetch all the message uids response, message_ids = self.server.uid('search', None, 'ALL')