user4530588
user4530588

Reputation:

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

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?

Upvotes: 7

Views: 14311

Answers (3)

coder
coder

Reputation: 4429

I would suggest do this,(Python 3)

typ, data = conn.fetch('1', '(RFC822)') # will read the first email
email_content = data[0][1] 
msg = email.message_from_bytes(email_content) # this needs to be corrected in your case 
emailDate =  msg["Date"]
emaiSubject = msg["Subject"]

Upvotes: 14

Ishan Anand
Ishan Anand

Reputation: 403

You can try:

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

Upvotes: 16

Mark R.
Mark R.

Reputation: 1323

You probably want to use a BytesHeaderParser in this case.

Upvotes: 0

Related Questions