Skip to content

Commit

Permalink
guess attachment mimetype in Django email backend if not provided
Browse files Browse the repository at this point in the history
* add test that demonstrates missing mimetype issue
* guess mimetype using python mimetypes lib if omitted
* add test with unguessable file type
* add fallback mimetype that django uses (application/octet-stream)
  • Loading branch information
HugoArts authored and richleland committed May 3, 2016
1 parent dc2cdd4 commit 05409ed
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
8 changes: 8 additions & 0 deletions sparkpost/django/message.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import mimetypes
from base64 import b64encode

from django.core.mail import EmailMultiAlternatives
from django.core.mail.message import DEFAULT_ATTACHMENT_MIME_TYPE
from django.conf import settings

from .exceptions import UnsupportedContent
Expand Down Expand Up @@ -63,6 +65,12 @@ def __init__(self, message):
str_encoding = settings.DEFAULT_CHARSET
for attachment in message.attachments:
filename, content, mimetype = attachment

if mimetype is None:
mimetype, _ = mimetypes.guess_type(filename)
if mimetype is None:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE

try:
if isinstance(content, unicode):
content = content.encode(str_encoding)
Expand Down
36 changes: 36 additions & 0 deletions test/django/test_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,42 @@ def test_attachment_unicode():
assert actual == expected


def test_attachment_guess_mimetype():
email_message = EmailMessage(**base_options)
email_message.attach('file.txt', 'test content')

actual = SparkPostMessage(email_message)
expected = dict(
attachments=[
{
'name': 'file.txt',
'data': 'dGVzdCBjb250ZW50',
'type': 'text/plain'
}
]
)
expected.update(base_expected)
assert actual == expected


def test_attachment_guess_mimetype_fallback():
email_message = EmailMessage(**base_options)
email_message.attach('file', 'test content')

actual = SparkPostMessage(email_message)
expected = dict(
attachments=[
{
'name': 'file',
'data': 'dGVzdCBjb250ZW50',
'type': 'application/octet-stream'
}
]
)
expected.update(base_expected)
assert actual == expected


def test_content_subtype():
email_message = EmailMessage(
to=['to@example.com'],
Expand Down

0 comments on commit 05409ed

Please sign in to comment.