Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

[1.0.X] Fixed #9367 - EmailMultiAlternatives does not properly handle…

… attachments.

Thanks to Loek Engels for the bulk of the patch.

Backport of r10983 from trunk


git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.0.X@10984 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit b9952794c387430e7c03510ad1a0db2497f1baf2 1 parent bbe034a
Luke Plant authored
87  django/core/mail.py
@@ -195,7 +195,7 @@ class EmailMessage(object):
195 195
     A container for email information.
196 196
     """
197 197
     content_subtype = 'plain'
198  
-    multipart_subtype = 'mixed'
  198
+    mixed_subtype = 'mixed'
199 199
     encoding = None     # None => use settings default
200 200
 
201 201
     def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
@@ -234,16 +234,7 @@ def message(self):
234 234
         encoding = self.encoding or settings.DEFAULT_CHARSET
235 235
         msg = SafeMIMEText(smart_str(self.body, settings.DEFAULT_CHARSET),
236 236
                            self.content_subtype, encoding)
237  
-        if self.attachments:
238  
-            body_msg = msg
239  
-            msg = SafeMIMEMultipart(_subtype=self.multipart_subtype)
240  
-            if self.body:
241  
-                msg.attach(body_msg)
242  
-            for attachment in self.attachments:
243  
-                if isinstance(attachment, MIMEBase):
244  
-                    msg.attach(attachment)
245  
-                else:
246  
-                    msg.attach(self._create_attachment(*attachment))
  237
+        msg = self._create_message(msg)
247 238
         msg['Subject'] = self.subject
248 239
         msg['From'] = self.extra_headers.pop('From', self.from_email)
249 240
         msg['To'] = ', '.join(self.to)
@@ -273,8 +264,7 @@ def send(self, fail_silently=False):
273 264
     def attach(self, filename=None, content=None, mimetype=None):
274 265
         """
275 266
         Attaches a file with the given filename and content. The filename can
276  
-        be omitted (useful for multipart/alternative messages) and the mimetype
277  
-        is guessed, if not provided.
  267
+        be omitted and the mimetype is guessed, if not provided.
278 268
 
279 269
         If the first parameter is a MIMEBase subclass it is inserted directly
280 270
         into the resulting message attachments.
@@ -292,15 +282,26 @@ def attach_file(self, path, mimetype=None):
292 282
         content = open(path, 'rb').read()
293 283
         self.attach(filename, content, mimetype)
294 284
 
295  
-    def _create_attachment(self, filename, content, mimetype=None):
  285
+    def _create_message(self, msg):
  286
+        return self._create_attachments(msg)
  287
+
  288
+    def _create_attachments(self, msg):
  289
+        if self.attachments:
  290
+            body_msg = msg
  291
+            msg = SafeMIMEMultipart(_subtype=self.mixed_subtype)
  292
+            if self.body:
  293
+                msg.attach(body_msg)
  294
+            for attachment in self.attachments:
  295
+                if isinstance(attachment, MIMEBase):
  296
+                    msg.attach(attachment)
  297
+                else:
  298
+                    msg.attach(self._create_attachment(*attachment))
  299
+        return msg
  300
+
  301
+    def _create_mime_attachment(self, content, mimetype):
296 302
         """
297  
-        Converts the filename, content, mimetype triple into a MIME attachment
298  
-        object.
  303
+        Converts the content, mimetype pair into a MIME attachment object.
299 304
         """
300  
-        if mimetype is None:
301  
-            mimetype, _ = mimetypes.guess_type(filename)
302  
-            if mimetype is None:
303  
-                mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
304 305
         basetype, subtype = mimetype.split('/', 1)
305 306
         if basetype == 'text':
306 307
             attachment = SafeMIMEText(smart_str(content,
@@ -310,6 +311,18 @@ def _create_attachment(self, filename, content, mimetype=None):
310 311
             attachment = MIMEBase(basetype, subtype)
311 312
             attachment.set_payload(content)
312 313
             Encoders.encode_base64(attachment)
  314
+        return attachment
  315
+
  316
+    def _create_attachment(self, filename, content, mimetype=None):
  317
+        """
  318
+        Converts the filename, content, mimetype triple into a MIME attachment
  319
+        object.
  320
+        """
  321
+        if mimetype is None:
  322
+            mimetype, _ = mimetypes.guess_type(filename)
  323
+            if mimetype is None:
  324
+                mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
  325
+        attachment = self._create_mime_attachment(content, mimetype)
313 326
         if filename:
314 327
             attachment.add_header('Content-Disposition', 'attachment',
315 328
                                   filename=filename)
@@ -321,11 +334,39 @@ class EmailMultiAlternatives(EmailMessage):
321 334
     messages. For example, including text and HTML versions of the text is
322 335
     made easier.
323 336
     """
324  
-    multipart_subtype = 'alternative'
  337
+    alternative_subtype = 'alternative'
325 338
 
326  
-    def attach_alternative(self, content, mimetype=None):
  339
+    def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
  340
+            connection=None, attachments=None, headers=None, alternatives=None):
  341
+        """
  342
+        Initialize a single email message (which can be sent to multiple
  343
+        recipients).
  344
+
  345
+        All strings used to create the message can be unicode strings (or UTF-8
  346
+        bytestrings). The SafeMIMEText class will handle any necessary encoding
  347
+        conversions.
  348
+        """
  349
+        super(EmailMultiAlternatives, self).__init__(subject, body, from_email, to, bcc, connection, attachments, headers)
  350
+        self.alternatives=alternatives or []
  351
+
  352
+    def attach_alternative(self, content, mimetype):
327 353
         """Attach an alternative content representation."""
328  
-        self.attach(content=content, mimetype=mimetype)
  354
+        assert content is not None
  355
+        assert mimetype is not None
  356
+        self.alternatives.append((content, mimetype))
  357
+
  358
+    def _create_message(self, msg):
  359
+        return self._create_attachments(self._create_alternatives(msg))
  360
+
  361
+    def _create_alternatives(self, msg):
  362
+        if self.alternatives:
  363
+            body_msg = msg
  364
+            msg = SafeMIMEMultipart(_subtype=self.alternative_subtype)
  365
+            if self.body:
  366
+                msg.attach(body_msg)
  367
+            for alternative in self.alternatives:
  368
+                msg.attach(self._create_mime_attachment(*alternative))
  369
+        return msg
329 370
 
330 371
 def send_mail(subject, message, from_email, recipient_list,
331 372
               fail_silently=False, auth_user=None, auth_password=None):
46  tests/regressiontests/mail/tests.py
@@ -2,7 +2,7 @@
2 2
 r"""
3 3
 # Tests for the django.core.mail.
4 4
 
5  
->>> from django.core.mail import EmailMessage
  5
+>>> from django.core.mail import EmailMessage, EmailMultiAlternatives
6 6
 >>> from django.utils.translation import ugettext_lazy
7 7
 
8 8
 # Test normal ascii character case:
@@ -67,4 +67,48 @@
67 67
 >>> message['From']
68 68
 'from@example.com'
69 69
 
  70
+# Handle attachments within an multipart/alternative mail correctly (#9367)
  71
+# (test is not as precise/clear as it could be w.r.t. email tree structure,
  72
+#  but it's good enough.)
  73
+
  74
+>>> headers = {"Date": "Fri, 09 Nov 2001 01:08:47 -0000", "Message-ID": "foo"}
  75
+>>> subject, from_email, to = 'hello', 'from@example.com', 'to@example.com'
  76
+>>> text_content = 'This is an important message.'
  77
+>>> html_content = '<p>This is an <strong>important</strong> message.</p>'
  78
+>>> msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers)
  79
+>>> msg.attach_alternative(html_content, "text/html")
  80
+>>> msg.attach("an attachment.pdf", "%PDF-1.4.%...", mimetype="application/pdf")
  81
+>>> print msg.message().as_string()
  82
+Content-Type: multipart/mixed; boundary="..."
  83
+MIME-Version: 1.0
  84
+Subject: hello
  85
+From: from@example.com
  86
+To: to@example.com
  87
+Date: Fri, 09 Nov 2001 01:08:47 -0000
  88
+Message-ID: foo
  89
+...
  90
+Content-Type: multipart/alternative; boundary="..."
  91
+MIME-Version: 1.0
  92
+...
  93
+Content-Type: text/plain; charset="utf-8"
  94
+MIME-Version: 1.0
  95
+Content-Transfer-Encoding: quoted-printable
  96
+...
  97
+This is an important message.
  98
+...
  99
+Content-Type: text/html; charset="utf-8"
  100
+MIME-Version: 1.0
  101
+Content-Transfer-Encoding: quoted-printable
  102
+...
  103
+<p>This is an <strong>important</strong> message.</p>
  104
+...
  105
+...
  106
+Content-Type: application/pdf
  107
+MIME-Version: 1.0
  108
+Content-Transfer-Encoding: base64
  109
+Content-Disposition: attachment; filename="an attachment.pdf"
  110
+...
  111
+JVBERi0xLjQuJS4uLg==
  112
+...
  113
+
70 114
 """

0 notes on commit b995279

Please sign in to comment.
Something went wrong with that request. Please try again.