TypeError: initial_value must be str or none, not bytes in python 3?

user4530588 picture user4530588 · Feb 18, 2015 · Viewed 11k times · Source

Here is my code:

import imaplib
from email.parser import HeaderParser
conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.login('[email protected]', 'password')
conn.select()
conn.search(None, 'ALL')
data = conn.fetch('1', '(BODY[HEADER])')
header_data = data[1][0][1]
parser = HeaderParser()
msg = parser.parsestr(header_data)

From this i get the error message:

TypeError: initial_value must be str or none, not bytes

Im using python 3 which apparently automatically decodes. So why am i still getting this error message?

Answer

Ishan Anand picture Ishan Anand · Feb 18, 2015

You can try:

header_data = data[1][0][1].decode('utf-8')