Skip to content

Commit

Permalink
Python2.7 import compatibility fix
Browse files Browse the repository at this point in the history
  • Loading branch information
cmccandless committed Oct 9, 2018
1 parent 2f77bb1 commit 064978b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
7 changes: 6 additions & 1 deletion sendgrid/helpers/mail/mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,14 @@ def from_EmailMessage(cls, message):
subject=message.get('Subject'),
to_email=Email(message.get('To')),
)
try:
body = message.get_content()
except AttributeError:
# Python2
body = message.get_payload()
mail.add_content(Content(
message.get_content_type(),
message.get_content()
body.strip()
))
for k, v in message.items():
mail.add_header(Header(k, v))
Expand Down
16 changes: 13 additions & 3 deletions test/test_mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@
import json
import unittest

from email.message import EmailMessage
try:
from email.message import EmailMessage
except ImportError:
# Python2
from email import message
EmailMessage = message.Message

from sendgrid.helpers.mail import (
ASM,
Expand Down Expand Up @@ -562,7 +567,12 @@ def test_directly_setting_substitutions(self):

def test_from_emailmessage(self):
message = EmailMessage()
message.set_content('message that is not urgent')
body = 'message that is not urgent'
try:
message.set_content(body)
except AttributeError:
# Python2
message.set_payload(body)
message.set_default_type('text/plain')
message['Subject'] = 'URGENT TITLE'
message['From'] = 'test@example.com'
Expand All @@ -576,4 +586,4 @@ def test_from_emailmessage(self):
self.assertEqual(len(mail.contents), 1)
content = mail.contents[0]
self.assertEqual(content.type, 'text/plain')
self.assertEqual(content.value, 'message that is not urgent\n')
self.assertEqual(content.value, 'message that is not urgent')

0 comments on commit 064978b

Please sign in to comment.