Stranger6667 / postmarker

Python client library for Postmark API
https://postmarker.readthedocs.io/en/stable/
MIT License
134 stars 29 forks source link

Automatically encode data to base64 if needed #153

Open Stranger6667 opened 6 years ago

Stranger6667 commented 6 years ago

Based on the discussion in #148.

Some data should be encoded to base64 before sending Example:

def text_and_text_attachment_failure():
    """
    This function sends a text body and text attachment.

    This function fails.
    """
    from django.core.mail import EmailMultiAlternatives
    msg = EmailMultiAlternatives(
        subject='Subject', body='Body', from_email='from@example.com',
        to=['to@example.com']
    )
    msg.attach('hello.txt', 'Hello World', 'text/plain')
    msg.send(fail_silently=False)

Output:

2018-05-27 09:23:24,588 - Postmarker - DEBUG - Request: POST https://api.postmarkapp.com/email/batch, Data: ({'TrackOpens': False, 'Attachments': [{'Name': 'hello.txt', 'Content': 'Hello World', 'ContentType': 'text/plain'}], 'TextBody': 'Body', 'From': 'from@example.com', 'Cc': None, 'ReplyTo': None, 'Bcc': None, 'To': 'to@example.com', 'Tag': None, 'HtmlBody': None, 'Headers': [], 'Subject': 'Subject'},)
2018-05-27 09:23:26,211 - Postmarker - DEBUG - Response: [{"ErrorCode":300,"Message":"Invalid attachment content - illegal base64 string."}]
Traceback (most recent call last):
  File "minimal.py", line 78, in <module>
    text_and_text_attachment_failure()
  File "minimal.py", line 70, in text_and_text_attachment_failure
    msg.send(fail_silently=False)
  File "/home/vagrant/postmarker-test/venv-django-1.11/lib/python3.5/site-packages/django/core/mail/message.py", line 348, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "/home/vagrant/postmarker-test/venv-django-1.11/lib/python3.5/site-packages/postmarker/django/backend.py", line 71, in send_messages
    self.raise_for_response(not_sent)
  File "/home/vagrant/postmarker-test/venv-django-1.11/lib/python3.5/site-packages/postmarker/django/backend.py", line 89, in raise_for_response
    raise PostmarkerException(message)
postmarker.exceptions.PostmarkerException: [300] Invalid attachment content - illegal base64 string.

Django automatically encodes some content - https://github.com/django/django/blob/master/django/core/mail/message.py#L358

So, the following is not encoded: