From 3ea8689ec0432c321538836412849e620c509a5c Mon Sep 17 00:00:00 2001 From: Adam Coddington Date: Sat, 22 Jun 2013 15:06:53 -0700 Subject: [PATCH] Encode message body to bytes prior to reconstituting e-mail message object. Added additional test to ensure that messages can make it the full cycle. --- django_mailbox/models.py | 16 +++++++++++++++- django_mailbox/tests/__init__.py | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/django_mailbox/models.py b/django_mailbox/models.py index 9e217b2..77c8482 100755 --- a/django_mailbox/models.py +++ b/django_mailbox/models.py @@ -394,7 +394,21 @@ class Message(models.Model): ).replace('=\n', '').rstrip('\n') def get_email_object(self): - return email.message_from_string(self.body) + """ Returns an `email.message.Message` instance for this message. + + Note: Python 2.6's version of email.message_from_string requires + bytes and will incorrectly create an e-mail object if a unicode + object is passed-in. + + Note that in reality 7-bit ascii *should* be an acceptable encoding + here per RFC-2822 (2.1), but given that `message_from_string` really + only cares that bytes are incoming rather than a unicode object, and + django will dutifully, if you were to edit the message in code or + via the admin, allow you to store unicode characters, returning UTF-8 + encoded bytes is probably the safest answer. + + """ + return email.message_from_string(self.body.encode('utf-8')) def delete(self, *args, **kwargs): for attachment in self.attachments.all(): diff --git a/django_mailbox/tests/__init__.py b/django_mailbox/tests/__init__.py index 83d18d1..5432b6e 100644 --- a/django_mailbox/tests/__init__.py +++ b/django_mailbox/tests/__init__.py @@ -155,3 +155,25 @@ class TestGetMessage(EmailMessageTestCase): actual_text, expected_text ) + + +class TestMessageGetEmailObject(TestCase): + def test_get_body_properly_handles_unicode_body(self): + with open( + os.path.join( + os.path.dirname(__file__), + 'generic_message.eml' + ) + ) as f: + unicode_body = unicode(f.read()) + + message = Message() + message.body = unicode_body + + expected_body = unicode_body + actual_body = message.get_email_object().as_string() + + self.assertEquals( + expected_body, + actual_body + )