Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #20 from elasticsales/master

Fix HTML emails with attachments.
  • Loading branch information...
commit 4a309e4ceef9476a5abd406b80e660af73d5c729 2 parents 2496c70 + 9797411
Matt Wright authored
Showing with 34 additions and 4 deletions.
  1. +5 −3 flask_mail.py
  2. +29 −1 tests.py
8 flask_mail.py
View
@@ -230,9 +230,11 @@ def as_string(self):
msg.attach(self._mimetext(self.body))
else:
# Anything else
- msg = MIMEMultipart('alternative')
- msg.attach(self._mimetext(self.body, 'plain'))
- msg.attach(self._mimetext(self.html, 'html'))
+ msg = MIMEMultipart()
+ alternative = MIMEMultipart('alternative')
+ alternative.attach(self._mimetext(self.body, 'plain'))
+ alternative.attach(self._mimetext(self.html, 'html'))
+ msg.attach(alternative)
msg['Subject'] = self.subject
msg['From'] = self.sender
30 tests.py
View
@@ -2,7 +2,8 @@
from __future__ import with_statement
-import email.utils
+import base64
+import email
import unittest
import time
import re
@@ -245,6 +246,33 @@ def test_html_message(self):
self.assertEqual(html_text, msg.html)
self.assertIn('Content-Type: multipart/alternative', msg.as_string())
+ def test_html_message_with_attachments(self):
+ html_text = "<p>Hello World</p>"
+ plain_text = 'Hello World'
+
+ msg = Message(subject="subject",
+ recipients=["to@example.com"],
+ body=plain_text,
+ html=html_text)
+
+ msg.attach(data="this is a test",
+ content_type="text/plain")
+
+ self.assertEqual(html_text, msg.html)
+ self.assertIn('Content-Type: multipart/alternative', msg.as_string())
+
+ parsed = email.message_from_string(msg.as_string())
+ self.assertEqual(len(parsed.get_payload()), 2)
+
+ body, attachment = parsed.get_payload()
+ self.assertEqual(len(body.get_payload()), 2)
+
+ plain, html = body.get_payload()
+ self.assertEqual(base64.b64decode(plain.get_payload()), plain_text)
+ self.assertEqual(base64.b64decode(html.get_payload()), html_text)
+
+ self.assertEqual(base64.b64decode(attachment.get_payload()), 'this is a test')
+
def test_date_header(self):
before = time.time()
Please sign in to comment.
Something went wrong with that request. Please try again.