Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #61: Handle text/* attachments passed as a text-string #70

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,10 @@ celerybeat-schedule
# dotenv
.env

# direnv
.direnv/
.envrc

# virtualenv
venv/
ENV/
47 changes: 34 additions & 13 deletions sgbackend/mail.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,21 +128,42 @@ def _build_sg_mail(self, email):
mail.set_reply_to(Email(reply_to_email))

for attachment in email.attachments:
filename, content, mimetype = (None, None, None)
if isinstance(attachment, MIMEBase):
attach = Attachment()
attach.set_filename(attachment.get_filename())
attach.set_content(base64.b64encode(attachment.get_payload()))
mail.add_attachment(attach)
elif isinstance(attachment, tuple):
attach = Attachment()
attach.set_filename(attachment[0])
base64_attachment = base64.b64encode(attachment[1])
if sys.version_info >= (3,):
attach.set_content(str(base64_attachment, 'utf-8'))
# If the attachment is a MIMEBase instance
filename = attachment.get_filename()
content = attachment.get_payload()
mimetype = attachment.get_content_type()
if attachment.get_content_maintype() == 'text' \
and isinstance(content, str):
content = base64.b64encode(
content.encode('utf-8')).decode('utf-8')
else:
attach.set_content(base64_attachment)
attach.set_type(attachment[2])
mail.add_attachment(attach)
content = base64.b64encode(content).decode('utf-8')

elif isinstance(attachment, tuple):
filename, content, mimetype = attachment
basetype, subtype = mimetype.split('/', 1)

if basetype == 'text' and isinstance(content, str):
# Django expects a text string if the MIME type is
# text/*, so we'll need to encode the string
content = base64.b64encode(
content.encode('utf-8')).decode('utf-8')

if isinstance(content, bytes):
# If the content is bytes, simply encode then convert
# to a text string
content = base64.b64encode(content).decode('utf-8')

assert content is not None

attach = Attachment()
attach.set_filename(filename)
attach.set_content(content)
attach.set_type(mimetype)

mail.add_attachment(attach)

mail.add_personalization(personalization)
return mail.get()
Empty file added tests/__init__.py
Empty file.
Binary file added tests/assets/test-image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
79 changes: 79 additions & 0 deletions tests/test_mail.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from email.mime.text import MIMEText

from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import EmailMessage
Expand Down Expand Up @@ -182,3 +184,80 @@ def test_build_sg_email_w_extra_headers(self):
'personalizations': [{'subject': ''}],
'subject': ''}
)

def test_build_sg_email_w_string_attachment(self):
"""
Test text/* attachment passed as a text string
"""
attachments = (('file.txt', 'String content', 'text/plain'),)
msg = EmailMessage(attachments=attachments)
with self.settings(SENDGRID_API_KEY='test_key'):
mail = SendGridBackend()._build_sg_mail(msg)
self.assertEqual(
mail,
{'from': {'email': 'webmaster@localhost'},
'subject': '', 'personalizations': [{'subject': ''}],
'content': [{'type': 'text/plain', 'value': ''}],
'attachments': [{
'content': 'U3RyaW5nIGNvbnRlbnQ=',
'type': 'text/plain',
'filename': 'file.txt'}]}
)

def test_build_sg_email_w_binary_attachment(self):
"""
Test text attachment passed as binary
"""
attachments = (('file.txt', b'Binary content', 'text/plain'),)
msg = EmailMessage(attachments=attachments)
with self.settings(SENDGRID_API_KEY='test_key'):
mail = SendGridBackend()._build_sg_mail(msg)
self.assertEqual(
mail,
{'from': {'email': 'webmaster@localhost'},
'subject': '', 'personalizations': [{'subject': ''}],
'content': [{'type': 'text/plain', 'value': ''}],
'attachments': [{
'content': 'QmluYXJ5IGNvbnRlbnQ=',
'type': 'text/plain',
'filename': 'file.txt'}]}
)

def test_build_sg_email_w_image_attachment(self):
"""
Test image attachment
"""
with open('tests/assets/test-image.png', 'rb') as f:
content = f.read()
attachments = (('file.png', content, 'image/png'),)
msg = EmailMessage(attachments=attachments)
with self.settings(SENDGRID_API_KEY='test_key'):
mail = SendGridBackend()._build_sg_mail(msg)
self.assertEqual(
mail,
{'from': {'email': 'webmaster@localhost'},
'subject': '', 'personalizations': [{'subject': ''}],
'content': [{'type': 'text/plain', 'value': ''}],
'attachments': [{
'content': 'iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAA8ElEQVR42o2TQQqCQBiFhdq5alFt3YbgBYICD+JB7AJ1AEFaiKtAOkRQ64iWgpjrVtU21P4f/oGHjDkDH/i/ee8xM6DVXfPpzCUSoiRqoRTNRa8unBHtAFlfOGeDIXk3fJSNOxEQD5lfQitaIJ6WMyrsQfPeGljsAb/HQgpCYlCQgD9loQLBNiiwwV+x0MjwtQwXeyXT8FCrRtMCOEHNQwGCbxD2wV+wEMM1PoTzJ+wQbyiIlcjDhjjI95VYQnBF3GQPcZQhYgH+gxMxgoKxJhx1j3cmnsSaWOgeDrj03XGrTH8KdkOvPCFCjR7yXlf/AfSXkoJCC4ZeAAAAAElFTkSuQmCC',
'type': 'image/png',
'filename': 'file.png'}]}
)

def test_build_sg_email_w_mimebase_attachment(self):
"""
Test MIMEBase attachment
"""
attachments = (MIMEText('Mime text', 'plain'), )
msg = EmailMessage(attachments=attachments)
with self.settings(SENDGRID_API_KEY='test_key'):
mail = SendGridBackend()._build_sg_mail(msg)
self.assertEqual(
mail,
{'from': {'email': 'webmaster@localhost'},
'subject': '', 'personalizations': [{'subject': ''}],
'content': [{'type': 'text/plain', 'value': ''}],
'attachments': [{
'content': 'TWltZSB0ZXh0',
'type': 'text/plain'}]}
)