Made email attachment handling code accept non-ASCII filenames.

Thanks to Anton Chaporgin for the report and to Claude Paroz for the patch.

Fixes #14964.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@17375 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Ramiro Morales 2012-01-15 02:33:31 +00:00
parent c5dcba4159
commit 665ec600a4
3 changed files with 20 additions and 1 deletions

View File

@ -311,6 +311,10 @@ class EmailMessage(object):
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
attachment = self._create_mime_attachment(content, mimetype)
if filename:
try:
filename = filename.encode('ascii')
except UnicodeEncodeError:
filename = ('utf-8', '', filename.encode('utf-8'))
attachment.add_header('Content-Disposition', 'attachment',
filename=filename)
return attachment

View File

@ -322,7 +322,9 @@ can be non-ASCII::
sender = u'Arnbjörg Ráðormsdóttir <arnbjorg@example.com>'
recipients = ['Fred <fred@example.com']
body = u'...'
EmailMessage(subject, body, sender, recipients).send()
msg = EmailMessage(subject, body, sender, recipients)
msg.attach(u"Une pièce jointe.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
msg.send()
Form submission
===============

View File

@ -198,6 +198,19 @@ class MailTests(TestCase):
self.assertEqual(payload[0].get_content_type(), 'multipart/alternative')
self.assertEqual(payload[1].get_content_type(), 'application/pdf')
def test_non_ascii_attachment_filename(self):
"""Regression test for #14964"""
headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
content = 'This is the message.'
msg = EmailMessage(subject, content, from_email, [to], headers=headers)
# Unicode in file name
msg.attach(u"une pièce jointe.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
msg_str = msg.message().as_string()
message = email.message_from_string(msg_str)
payload = message.get_payload()
self.assertEqual(payload[1].get_filename(), u'une pièce jointe.pdf')
def test_dummy_backend(self):
"""
Make sure that dummy backends returns correct number of sent messages