Skip to content

Commit

Permalink
Handle emails with HTML alternatives and attachments (#149)
Browse files Browse the repository at this point in the history
* Handle emails with HTML alternatives and attachments

Fixes issue #148

* Fix lint
  • Loading branch information
suriya authored and Stranger6667 committed Jun 5, 2018
1 parent a49b5b9 commit 90ad813
Showing 1 changed file with 24 additions and 16 deletions.
40 changes: 24 additions & 16 deletions postmarker/models/emails.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,19 +77,30 @@ def prepare_attachments(attachment):
return result


def deconstruct_multipart(message):
text, html, attachments = None, None, []
for part in message.walk():
if part is message:
continue
content_type = part.get_content_type()
if content_type == 'text/plain' and text is None:
text = part.get_payload(decode=True).decode('utf8')
elif content_type == 'text/html' and html is None:
html = part.get_payload(decode=True).decode('utf8')
def deconstruct_multipart_recursive(seen, text, html, attachments, message):
if message in seen:
return
seen.add(message)
if isinstance(message, MIMEMultipart):
for part in message.walk():
deconstruct_multipart_recursive(seen, text, html, attachments, part)
else:
content_type = message.get_content_type()
if content_type == 'text/plain' and not text:
text.append(message.get_payload(decode=True).decode('utf8'))
elif content_type == 'text/html' and not html:
html.append(message.get_payload(decode=True).decode('utf8'))
else:
attachments.append(part)
return text, html, attachments
attachments.append(message)


def deconstruct_multipart(message):
seen = set()
text = []
html = []
attachments = []
deconstruct_multipart_recursive(seen, text, html, attachments, message)
return (text and text[0]) or None, (html and html[0]) or None, attachments


class BaseEmail(Model):
Expand Down Expand Up @@ -178,10 +189,7 @@ def from_mime(cls, message, manager):
:param manager: :py:class:`EmailManager` instance.
:return: :py:class:`Email`
"""
if isinstance(message, MIMEMultipart):
text, html, attachments = deconstruct_multipart(message)
else:
text, html, attachments = message.get_payload(decode=True).decode('utf8'), None, []
text, html, attachments = deconstruct_multipart(message)
subject = prepare_header(message['Subject'])
sender = prepare_header(message['From'])
to = prepare_header(message['To'])
Expand Down

0 comments on commit 90ad813

Please sign in to comment.