stmplib MIMEText charset weirdness

Adam W. AWasilenko at
Tue Feb 26 05:00:24 CET 2013

Can someone explain to me why I can't set the charset after the fact and still have it work.

For example:
>>> text = MIMEText('❤¥'.encode('utf-8'), 'html')
>>> text.set_charset('utf-8')
>>> text.as_string()
Traceback (most recent call last):
  File "<pyshell#53>", line 1, in <module>
  File "C:\Python32\lib\email\", line 168, in as_string
    g.flatten(self, unixfrom=unixfrom)
  File "C:\Python32\lib\email\", line 91, in flatten
  File "C:\Python32\lib\email\", line 137, in _write
  File "C:\Python32\lib\email\", line 163, in _dispatch
  File "C:\Python32\lib\email\", line 192, in _handle_text
    raise TypeError('string payload expected: %s' % type(payload))
TypeError: string payload expected: <class 'bytes'>

As opposed to:
>>> text = MIMEText('❤¥'.encode('utf-8'), 'html', 'utf-8')
>>> text.as_string()
'Content-Type: text/html; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: base64\n\n4p2kwqU=\n'

Side question:
>>> text = MIMEText('❤¥', 'html')
>>> text.set_charset('utf-8')
>>> text.as_string()
'MIME-Version: 1.0\nContent-Transfer-Encoding: 8bit\nContent-Type: text/html; charset="utf-8"\n\n❤¥'

Why is it now 8-bit encoding?

More information about the Python-list mailing list