spam spamthis works for textbut watch what happens when we try to render message part with truly binary datasuch as an image that could not be decoded as unicode textfrom email message import message generic message object message( ['from''bob@bob combytes open('monkeys jpg''rb'read(read binary bytes (not unicodem set_payload(byteswe set the payload to bytes print(mtraceback (most recent call last)lines omitted file " :\python \lib\email\generator py"line in _handle_text raise typeerror('string payload expected%stype(payload)typeerrorstring payload expectedm get_payload()[: '\xff\xd \xff\xe \ \ jfif\ \ \ \ \ \ \ \ the problem here is that the email package' text generator assumes that the message' payload data is base (or similarencoded str text string by generation timenot bytes reallythe error is probably our fault in this casebecause we set the payload to raw bytes manually we should use the mimeimage mime subclass tailored for imagesif we dothe email package internally performs base mime email encoding on the data when the message object is created unfortunatelyit still leaves it as bytesnot strdespite the fact the whole point of base is to change binary data to text (though the exact unicode flavor this text should take may be unclearthis leads to additional failures in python from email mime image import mimeimage message sublcass with hdrs+base bytes open('monkeys jpg''rb'read(read binary bytes again mimeimage(bytesmime class does base on data print(mtraceback (most recent call last)lines omitted file " :\python \lib\email\generator py"line in _handle_text raise typeerror('string payload expected%stype(payload)typeerrorstring payload expectedm get_payload()[: '/ / aaqskzjrgabaqeaeab aad/ wbdaaibaqibthis is already base text get_payload()[: decode('ascii''/ / aaqskzjrgabaqeaeab aad/ wbdaaibaqibbut it' still bytes internallyin other wordsnot only does the python email package not fully support the python unicode/bytes dichotomyit was actually broken by it luckilythere' workaround for this case to address this specific issuei opted to create custom encoding function for binary mime attachmentsand pass it in to the email package' mime message object emailparsing and composing mail content