Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3: Send email message containing binary data?

The following fails:

>>> a = email.message.Message()
>>> a.set_payload(b'some data')
>>> a.as_string()
TypeError: string payload expected: <class 'bytes'>

It also fails using a generator explicitly, and calling flatten. The message body is converted to ASCII, escapes applied and then finally converted to bytes for transmission anyway, so why can I not set a bytes payload?

How do I go about getting a preferably non-MIME message with a bytes payload that smtplib.SMTP.send_message will accept?

like image 667
Matt Joiner Avatar asked Nov 14 '22 20:11

Matt Joiner


1 Answers

Remember: in Python 3 strings are all unicode. You are effectively giving Python a bytes object and then telling it you want a unicode string, but not telling it which encoding to use to convert the bytes object to a string.

What you need to do is provide the encoding as the second parameter to the set_payload() call, like so:

test = email.message.Message()
test.set_payload(b'some example_data', 'latin1') # use latin-1 for no-op translation
test.as_string()

'MIME-Version: 1.0\nContent-Type: text/plain; charset="latin1"\nContent-Transfer-Encoding: base64\n\nc29tZSBleGFtcGxlIGRhdGE=\n'

This does give a MIME type message -- hopefully that will work for you.

like image 88
Ethan Furman Avatar answered Dec 06 '22 07:12

Ethan Furman