Merge pull request #65 from winhamwr/unicode_attachments

`UnicodeEncodeError` with unicode attachments
This commit is contained in:
Mike Edmunds
2014-05-28 09:03:12 -07:00
2 changed files with 31 additions and 7 deletions

View File

@@ -294,15 +294,18 @@ class DjrillBackend(BaseEmailBackend):
if mimetype is None: if mimetype is None:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
# b64encode requires bytes, so let's convert our content.
try: try:
content_b64 = b64encode(content) if isinstance(content, unicode):
except TypeError: # Python 2.X unicode string
# Python 3 b64encode requires bytes. Convert str attachment: content = content.encode(str_encoding)
except NameError:
# Python 3 doesn't differentiate between strings and unicode
# Convert python3 unicode str to bytes attachment:
if isinstance(content, str): if isinstance(content, str):
content_bytes = content.encode(str_encoding) content = content.encode(str_encoding)
content_b64 = b64encode(content_bytes)
else: content_b64 = b64encode(content)
raise
mandrill_attachment = { mandrill_attachment = {
'type': mimetype, 'type': mimetype,

View File

@@ -1,3 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from base64 import b64decode from base64 import b64decode
from datetime import date, datetime, timedelta, tzinfo from datetime import date, datetime, timedelta, tzinfo
from email.mime.base import MIMEBase from email.mime.base import MIMEBase
@@ -177,6 +181,23 @@ class DjrillBackendTests(DjrillBackendMockAPITestCase):
# Make sure the image attachment is not treated as embedded: # Make sure the image attachment is not treated as embedded:
self.assertFalse('images' in data['message']) self.assertFalse('images' in data['message'])
def test_unicode_attachment_correctly_decoded(self):
msg = mail.EmailMessage(
subject='Subject',
body='Body goes here',
from_email='from@example.com',
to=['to1@example.com'],
)
# Slight modification from the Django unicode docs:
# http://django.readthedocs.org/en/latest/ref/unicode.html#email
msg.attach("Une pièce jointe.html", '<p>\u2019</p>', mimetype='text/html')
msg.send()
data = self.get_api_call_data()
attachments = data['message']['attachments']
self.assertEqual(len(attachments), 1)
def test_embedded_images(self): def test_embedded_images(self):
image_data = self.sample_image_content() # Read from a png file image_data = self.sample_image_content() # Read from a png file
image_cid = make_msgid("img") # Content ID per RFC 2045 section 7 (with <...>) image_cid = make_msgid("img") # Content ID per RFC 2045 section 7 (with <...>)