themartorana / python-postmark

Postmark library for Python 2.6 and greater
http://davemartorana.com
MIT License
199 stars 83 forks source link

PMMail message.send() fails when trying to serialize byte string attachment with json.dumps() #93

Closed parappathekappa closed 3 years ago

parappathekappa commented 3 years ago

Version 0.5.5 Python 3.7.5 Django 2.2.10

Attempt to attach a file to a new PMMail message as a byte string, using the list of tuples format, and send() it.

    message = PMMail(
        api_key=os.environ.get('POSTMARK_API_KEY'),
        subject=subject,
        sender=os.environ.get('POSTMARK_SENDER'),
        to=recipient,
        text_body=text_body,
        html_body=html_body,
        attachments=attachments,
        tag=tag)
    message.send()

Where

attachments = [
            (
                "csv_file.csv",
                b'TXkgbmV3IHN0cmluZy4=',
                "text/csv"
            )
        ]

Error returned is:

 [('csv_file.csv', b'TXkgbmV3IHN0cmluZy4=', 'text/csv')]
 Object of type bytes is not JSON serializable
 Traceback (most recent call last):
   File "/app/apps/chipapp/tasks/emails.py", line 451, in _send_email_with_attachments
     message.send()
   File "/app/.heroku/python/lib/python3.7/site-packages/postmark/core.py", line 513, in send
     json.dumps(json_message, cls=PMJSONEncoder).encode('utf8'),
   File "/app/.heroku/python/lib/python3.7/json/__init__.py", line 238, in dumps
     **kw).encode(obj)
   File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 199, in encode
     chunks = self.iterencode(o, _one_shot=True)
   File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 257, in iterencode
     return _iterencode(o, 0)
   File "/app/.heroku/python/lib/python3.7/site-packages/postmark/core.py", line 40, in default
     return super(PMJSONEncoder, self).default(o)
   File "/app/.heroku/python/lib/python3.7/json/encoder.py", line 179, in default
     raise TypeError(f'Object of type {o.__class__.__name__} '
 TypeError: Object of type bytes is not JSON serializable
parappathekappa commented 3 years ago

NVM, got it working by decode() ing the original byte string.