forked from mirror/django-mailbox
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.
This commit is contained in:
parent
9cdb2d9d1b
commit
3ea8689ec0
2 changed files with 37 additions and 1 deletions
|
|
@ -394,7 +394,21 @@ class Message(models.Model):
|
||||||
).replace('=\n', '').rstrip('\n')
|
).replace('=\n', '').rstrip('\n')
|
||||||
|
|
||||||
def get_email_object(self):
|
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):
|
def delete(self, *args, **kwargs):
|
||||||
for attachment in self.attachments.all():
|
for attachment in self.attachments.all():
|
||||||
|
|
|
||||||
|
|
@ -155,3 +155,25 @@ class TestGetMessage(EmailMessageTestCase):
|
||||||
actual_text,
|
actual_text,
|
||||||
expected_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
|
||||||
|
)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue