Skip to content
This repository
Browse code

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 2 changed files with 34 additions and 4 deletions. Show diff stats Hide diff stats

  1. +5 3 flask_mail.py
  2. +29 1 tests.py
8 flask_mail.py
@@ -230,9 +230,11 @@ def as_string(self):
230 230 msg.attach(self._mimetext(self.body))
231 231 else:
232 232 # Anything else
233   - msg = MIMEMultipart('alternative')
234   - msg.attach(self._mimetext(self.body, 'plain'))
235   - msg.attach(self._mimetext(self.html, 'html'))
  233 + msg = MIMEMultipart()
  234 + alternative = MIMEMultipart('alternative')
  235 + alternative.attach(self._mimetext(self.body, 'plain'))
  236 + alternative.attach(self._mimetext(self.html, 'html'))
  237 + msg.attach(alternative)
236 238
237 239 msg['Subject'] = self.subject
238 240 msg['From'] = self.sender
30 tests.py
@@ -2,7 +2,8 @@
2 2
3 3 from __future__ import with_statement
4 4
5   -import email.utils
  5 +import base64
  6 +import email
6 7 import unittest
7 8 import time
8 9 import re
@@ -245,6 +246,33 @@ def test_html_message(self):
245 246 self.assertEqual(html_text, msg.html)
246 247 self.assertIn('Content-Type: multipart/alternative', msg.as_string())
247 248
  249 + def test_html_message_with_attachments(self):
  250 + html_text = "<p>Hello World</p>"
  251 + plain_text = 'Hello World'
  252 +
  253 + msg = Message(subject="subject",
  254 + recipients=["to@example.com"],
  255 + body=plain_text,
  256 + html=html_text)
  257 +
  258 + msg.attach(data="this is a test",
  259 + content_type="text/plain")
  260 +
  261 + self.assertEqual(html_text, msg.html)
  262 + self.assertIn('Content-Type: multipart/alternative', msg.as_string())
  263 +
  264 + parsed = email.message_from_string(msg.as_string())
  265 + self.assertEqual(len(parsed.get_payload()), 2)
  266 +
  267 + body, attachment = parsed.get_payload()
  268 + self.assertEqual(len(body.get_payload()), 2)
  269 +
  270 + plain, html = body.get_payload()
  271 + self.assertEqual(base64.b64decode(plain.get_payload()), plain_text)
  272 + self.assertEqual(base64.b64decode(html.get_payload()), html_text)
  273 +
  274 + self.assertEqual(base64.b64decode(attachment.get_payload()), 'this is a test')
  275 +
248 276 def test_date_header(self):
249 277 before = time.time()
250 278

0 comments on commit 4a309e4

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