Use MIMEBase method of attaching

This commit is contained in:
shamoon 2025-01-16 00:11:51 -08:00
parent 8e6063ab11
commit 93846e2f43
2 changed files with 24 additions and 3 deletions

View File

@ -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):

View File

@ -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}",