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

guess attachment mimetype in Django email backend if not provided #115

Merged
merged 4 commits into from
May 3, 2016
Merged
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
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=['[email protected]'],
Expand Down