diff --git a/src/documents/tests/test_api_documents.py b/src/documents/tests/test_api_documents.py index 630aeaee2..3be61d1d8 100644 --- a/src/documents/tests/test_api_documents.py +++ b/src/documents/tests/test_api_documents.py @@ -2698,7 +2698,7 @@ class TestDocumentApi(DirectoriesMixin, DocumentConsumeDelayMixin, APITestCase): ) self.assertEqual(len(mail.outbox), 1) - self.assertEqual(mail.outbox[0].attachments[0][0], "archive.pdf") + self.assertEqual(mail.outbox[0].attachments[0].get_filename(), "archive.pdf") self.client.post( f"/api/documents/{doc2.pk}/email/", @@ -2711,7 +2711,7 @@ class TestDocumentApi(DirectoriesMixin, DocumentConsumeDelayMixin, APITestCase): ) self.assertEqual(len(mail.outbox), 2) - self.assertEqual(mail.outbox[1].attachments[0][0], "test2.pdf") + self.assertEqual(mail.outbox[1].attachments[0].get_filename(), "test2.pdf") @mock.patch("django.core.mail.message.EmailMessage.send", side_effect=Exception) def test_email_document_errors(self, mocked_send): diff --git a/src/documents/views.py b/src/documents/views.py index 8e61f74f0..35f208709 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -8,6 +8,9 @@ import tempfile import urllib import zipfile from datetime import datetime +from email.encoders import encode_base64 +from email.mime.base import MIMEBase +from email.utils import encode_rfc2231 from pathlib import Path from time import mktime from unicodedata import normalize @@ -1065,7 +1068,25 @@ class DocumentViewSet( if use_archive_version and doc.has_archive_version else doc.source_path ) - email.attach_file(attachment) + with open(attachment, "rb") as f: + file_content = f.read() + + main_type, sub_type = ( + doc.mime_type.split("/", 1) + if doc.mime_type + else ("application", "octet-stream") + ) + mime_part = MIMEBase(main_type, sub_type) + mime_part.set_payload(file_content) + + encode_base64(mime_part) + + mime_part.add_header( + "Content-Disposition", + f'attachment; filename="{encode_rfc2231(str(attachment.name))}"', + ) + + email.attach(mime_part) email.send() logger.debug( f"Sent document {doc.id} via email to {addresses}",