From 7e250b2504a9510a46ef601b25ab1907719f9e3f Mon Sep 17 00:00:00 2001 From: Martin Manzo Date: Fri, 11 Aug 2023 10:33:45 -0300 Subject: [PATCH] Close attachments --- .gitignore | 1 + django_mailbox/models.py | 36 +++++++++++++++++------------------- 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/.gitignore b/.gitignore index 94fab772..9209014c 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ dummy_project/* messages *.sqlite3 .idea/ +venv/ \ No newline at end of file diff --git a/django_mailbox/models.py b/django_mailbox/models.py index 871b0ccb..e24e9c5e 100644 --- a/django_mailbox/models.py +++ b/django_mailbox/models.py @@ -677,7 +677,6 @@ def html(self): def _rehydrate(self, msg): new = EmailMessage() settings = utils.get_settings() - if msg.is_multipart(): for header, value in msg.items(): new[header] = value @@ -696,24 +695,24 @@ def _rehydrate(self, msg): if encoding and encoding.lower() == 'quoted-printable': # Cannot use `email.encoders.encode_quopri due to # bug 14360: http://bugs.python.org/issue14360 - output = BytesIO() - encode_quopri( - BytesIO( - attachment.document.read() - ), - output, - quotetabs=True, - header=False, - ) - new.set_payload( - output.getvalue().decode().replace(' ', '=20') - ) + with open(attachment.document.path, 'rb') as f: + output = BytesIO() + encode_quopri( + BytesIO( + f.read() + ), + output, + quotetabs=True, + header=False, + ) + new.set_payload( + output.getvalue().decode().replace(' ', '=20') + ) del new['Content-Transfer-Encoding'] new['Content-Transfer-Encoding'] = 'quoted-printable' else: - new.set_payload( - attachment.document.read() - ) + with open(attachment.document.path, 'rb') as f: + new.set_payload(f.read()) del new['Content-Transfer-Encoding'] encode_base64(new) except MessageAttachment.DoesNotExist: @@ -777,9 +776,8 @@ def get_email_object(self): if self.eml.name.endswith('.gz'): body = gzip.GzipFile(fileobj=self.eml).read() else: - self.eml.open() - body = self.eml.file.read() - self.eml.close() + with self.eml.open(): + body = self.eml.file.read() else: body = self.get_body() flat = email.message_from_bytes(body)