Commits

Anonymous committed 5623c8c

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.

Comments (0)

Files changed (3)

django/core/mail/message.py

                 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
     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
 ===============

tests/regressiontests/mail/tests.py

         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