1
0
Fork 0

Merge pull request #284 from the-maverick-lab/akshet/close-connection

Close connections after we are done with them
This commit is contained in:
Pietro 2024-03-09 15:02:48 +01:00 committed by GitHub
commit f4a0782d3d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 23 additions and 16 deletions

View file

@ -470,15 +470,18 @@ class Mailbox(models.Model):
connection = self.get_connection() connection = self.get_connection()
if not connection: if not connection:
return return
for message in connection.get_message(condition): try:
msg = self.process_incoming_message(message) for message in connection.get_message(condition):
if msg is not None: msg = self.process_incoming_message(message)
yield msg if msg is not None:
self.last_polling = now() yield msg
if django.VERSION >= (1, 5): # Django 1.5 introduces update_fields self.last_polling = now()
self.save(update_fields=['last_polling']) if django.VERSION >= (1, 5): # Django 1.5 introduces update_fields
else: self.save(update_fields=['last_polling'])
self.save() else:
self.save()
finally:
connection.close()
@staticmethod @staticmethod
def get_new_mail_all_mailboxes(args=None): def get_new_mail_all_mailboxes(args=None):

View file

@ -9,3 +9,6 @@ class EmailTransport:
message = email.message_from_bytes(contents) message = email.message_from_bytes(contents)
return message return message
def close(self):
pass

View file

@ -6,13 +6,6 @@ from django.conf import settings
from .base import EmailTransport, MessageParseError 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__) logger = logging.getLogger(__name__)
@ -56,6 +49,14 @@ class ImapTransport(EmailTransport):
else: else:
self.server.select() 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): def _get_all_message_ids(self):
# Fetch all the message uids # Fetch all the message uids
response, message_ids = self.server.uid('search', None, 'ALL') response, message_ids = self.server.uid('search', None, 'ALL')