Skip to content
This repository has been archived by the owner on Feb 22, 2024. It is now read-only.

Commit

Permalink
Merge pull request #20 from elasticsales/master
Browse files Browse the repository at this point in the history
Fix HTML emails with attachments.
  • Loading branch information
Matt Wright committed Oct 8, 2012
2 parents 2496c70 + 9797411 commit 4a309e4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
8 changes: 5 additions & 3 deletions flask_mail.py
Expand Up @@ -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
Expand Down
30 changes: 29 additions & 1 deletion tests.py
Expand Up @@ -2,7 +2,8 @@

from __future__ import with_statement

import email.utils
import base64
import email
import unittest
import time
import re
Expand Down Expand Up @@ -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()

Expand Down

0 comments on commit 4a309e4

Please sign in to comment.