From 7eddee4271547e8aee1ca78d512347fdeaa7261e Mon Sep 17 00:00:00 2001 From: Corey McCandless Date: Thu, 4 Oct 2018 09:01:03 -0400 Subject: [PATCH] Python2.7 import compatibility fix --- sendgrid/helpers/mail/mail.py | 7 ++++++- test/test_mail.py | 16 +++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/sendgrid/helpers/mail/mail.py b/sendgrid/helpers/mail/mail.py index a6253f675..0f11428da 100644 --- a/sendgrid/helpers/mail/mail.py +++ b/sendgrid/helpers/mail/mail.py @@ -411,9 +411,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)) diff --git a/test/test_mail.py b/test/test_mail.py index 8c61f1dfb..557c6abd7 100644 --- a/test/test_mail.py +++ b/test/test_mail.py @@ -1,7 +1,12 @@ # -*- coding: utf-8 -*- import json -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, @@ -589,7 +594,12 @@ def test_dynamic_template_data(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' @@ -603,4 +613,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')