>>> m = Message()
>>> m.add_header('Content-Type', 'text/plain')
>>> m['MIME-Version'] = '1.0'
>>> m.set_param('charset', 'us-ascii')
>>> m.add_header('Content-Transfer-Encoding', '7bit')
>>> data = b'spam'
>>> m.set_payload(data.decode('ascii')) # data read as bytes here
>>> print(m)
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
spam
>>> print(MIMEText('spam', _charset='ascii')) # same, but type-specific
MIME-Version: 1.0
Content-Type: text/plain; charset="us-ascii"
Content-Transfer-Encoding: 7bit
spam
To do the same for other kinds of text that require MIME encoding, just insert an extra
encoding step; although we’re concerned with text parts here, a similar imitative ap-
proach could address the binary parts text generation bug we met earlier:
>>> m = Message()
>>> m.add_header('Content-Type', 'text/plain')
>>> m['MIME-Version'] = '1.0'
>>> m.set_param('charset', 'utf-8')
>>> m.add_header('Content-Transfer-Encoding', 'base64')
>>> data = b'spam'
>>> from binascii import b2a_base64 # add MIME encode if needed
>>> data = b2a_base64(data) # data read as bytes here too
>>> m.set_payload(data.decode('ascii'))
>>> print(m)
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: base64
c3BhbQ==
>>> print(MIMEText(b'spam', _charset='utf-8')) # same, but type-specific
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: base64
c3BhbQ==
This works, but besides the redundancy and dependency it creates, to use this approach
broadly we’d also have to generalize to account for all the various kinds of Unicode
encodings and MIME encodings possible, like the email package already does inter-
nally. We might also have to support encoding name synonyms to be flexible, adding
further redundancy. In other words, this requires additional work, and in the end, we’d
still have to specialize our code for different Unicode types.
email: Parsing and Composing Mail Content | 945