Skip to content

Commit

Permalink
Merge pull request BradWhittington#9 from ephemerallabs/attachments
Browse files Browse the repository at this point in the history
A better handling of attachments
  • Loading branch information
pydanny committed Sep 9, 2015
2 parents 3c366be + 0e72f8c commit 08f9715
Showing 1 changed file with 29 additions and 17 deletions.
46 changes: 29 additions & 17 deletions django_mailgun/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from django.utils.six import StringIO
from django.utils.encoding import smart_text

from requests.packages.urllib3.filepost import encode_multipart_formdata

class MailgunAPIError(Exception):
pass
Expand All @@ -29,7 +28,7 @@ def __init__(self, fail_silently=False, *args, **kwargs):
self._server_name = server_name or getattr(settings, 'MAILGUN_SERVER_NAME')
except AttributeError:
if fail_silently:
self._access_key, self._server_name = None, None
self._access_key, self._server_name = None
else:
raise

Expand All @@ -53,27 +52,40 @@ def _send(self, email_message):
recipients = [sanitize_address(addr, email_message.encoding)
for addr in email_message.recipients()]

message = smart_text(email_message.message().as_string(), errors='ignore')
try:
r = requests.\
post(self._api_url + "messages.mime",
auth=("api", self._access_key),
data={
"to": ", ".join(recipients),
"from": from_email,
},
files={
"message": StringIO(message),
}
)

post_data = []
post_data.append(('to', (",".join(recipients)),))
post_data.append(('text', email_message.body,))
post_data.append(('subject', email_message.subject,))
post_data.append(('from', from_email,))

if hasattr(email_message, 'alternatives') and email_message.alternatives:
for alt in email_message.alternatives:
if alt[1] == 'text/html':
post_data.append(('html', alt[0],))
break

if email_message.attachments:
for attachment in email_message.attachments:
post_data.append(('attachment', (attachment[0], attachment[1],)))
content, header = encode_multipart_formdata(post_data)
headers = {'Content-Type': header}
else:
content = post_data
headers = None

response = requests.post(self._api_url + "messages",
auth=("api", self._access_key),
data=content, headers=headers)
except:
if not self.fail_silently:
raise
return False

if r.status_code != 200:
if response.status_code != 200:
if not self.fail_silently:
raise MailgunAPIError(r)
raise MailgunAPIError(response)
return False

return True
Expand Down

0 comments on commit 08f9715

Please sign in to comment.