Python Forum

Full Version: TypeError: initial_value must be str or None, not bytes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all

Here is a snapshot of my code:

for num in data[0].split():
    typ, data = mail.fetch(num,'(RFC822)')


    for response_part in data:
        if isinstance(response_part, tuple):
            msg = email.message_from_string(response_part[1])
Error comes from:
msg = email.message_from_string(response_part[1])
Error message:
TypeError: initial_value must be str or None, not bytes
Have been looking at google for an hour now, and Ive tried playing around with the is.BytesIO and StringIO but I just cant get it working. The problem seems to have something to do with the difference between Python 2 and 3.

Kind Regards,
Peter

I tried:

msg = io.StringIO(email.message_from_string(response_part[1]))
Doesn't help

Br, Peter
Try:
msg = email.message_from_string(response_part[1].decode())
Everything that comes in from outside into Python 3 most have a encoding so it will be Unicode,
if not it will be bytes.
That's because Python 3 has full Unicode support and will not mix stuff together in a string like Python 2 did.
>>> s = b'hello'
>>> type(s)
<class 'bytes'>

# Convert to string(which is Unicode bye default Python 3)
>>> s.decode()
'hello'
>>> # Same as 
>>> s.decode('utf-8')
'hello'
>>> type(s.decode())
<class 'str'>
Brilliant it works as a charm..

Many thanks!
Br, Peter