Fixed crasher when sending rfc822 messages as attachments. (#59)

This commit is contained in:
Luke Plant
2017-04-15 21:45:32 +03:00
committed by Mike Edmunds
parent 7b010ab224
commit 7d7448011b
3 changed files with 33 additions and 2 deletions

View File

@@ -1,6 +1,14 @@
# -*- coding: utf-8 -*-
from datetime import date, datetime
try:
from email import message_from_bytes
except ImportError:
from email import message_from_string
def message_from_bytes(s):
return message_from_string(s.decode('utf-8'))
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
@@ -14,7 +22,7 @@ from anymail.exceptions import AnymailAPIError, AnymailRequestsAPIError, Anymail
from anymail.message import attach_inline_image_file
from .mock_requests_backend import RequestsBackendMockAPITestCase, SessionSharingTestCasesMixin
from .utils import sample_image_content, sample_image_path, SAMPLE_IMAGE_FILENAME, AnymailTestMixin
from .utils import sample_image_content, sample_image_path, SAMPLE_FORWARDED_EMAIL, SAMPLE_IMAGE_FILENAME, AnymailTestMixin
@override_settings(EMAIL_BACKEND='anymail.backends.mailgun.EmailBackend',
@@ -131,13 +139,27 @@ class MailgunBackendStandardEmailTests(MailgunBackendMockAPITestCase):
mimeattachment.set_payload(pdf_content)
self.message.attach(mimeattachment)
# And also with an message/rfc822 attachment
forwarded_email = message_from_bytes(SAMPLE_FORWARDED_EMAIL)
rfcmessage = MIMEBase("message", "rfc822")
rfcmessage.attach(forwarded_email)
self.message.attach(rfcmessage)
self.message.send()
files = self.get_api_call_files()
attachments = [value for (field, value) in files if field == 'attachment']
self.assertEqual(len(attachments), 3)
self.assertEqual(len(attachments), 4)
self.assertEqual(attachments[0], ('test.txt', text_content, 'text/plain'))
self.assertEqual(attachments[1], ('test.png', png_content, 'image/png')) # type inferred from filename
self.assertEqual(attachments[2], (None, pdf_content, 'application/pdf')) # no filename
# Email messages can get a bit changed with respect to
# whitespace characters in headers, without breaking the message, so we
# tolerate that:
self.assertEqual(attachments[3][0], None)
self.assertEqual(attachments[3][1].replace(b'\n', b'').replace(b' ', b''),
(b'Content-Type: message/rfc822\nMIME-Version: 1.0\n\n' + SAMPLE_FORWARDED_EMAIL).replace(b'\n', b'').replace(b' ', b''))
self.assertEqual(attachments[3][2], 'message/rfc822')
# Make sure the image attachment is not treated as embedded:
inlines = [value for (field, value) in files if field == 'inline']
self.assertEqual(len(inlines), 0)