Skip to content

Commit

Permalink
Merge pull request #284 from the-maverick-lab/akshet/close-connection
Browse files Browse the repository at this point in the history
Close connections after we are done with them
  • Loading branch information
Pietro395 authored Mar 9, 2024
2 parents 592126c + f91b4ee commit f4a0782
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 16 deletions.
21 changes: 12 additions & 9 deletions django_mailbox/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
3 changes: 3 additions & 0 deletions django_mailbox/transports/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,6 @@ def get_email_from_bytes(self, contents):
message = email.message_from_bytes(contents)

return message

def close(self):
pass
15 changes: 8 additions & 7 deletions django_mailbox/transports/imap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)


Expand Down Expand Up @@ -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')
Expand Down

0 comments on commit f4a0782

Please sign in to comment.