'str' object has no attribute 'decode'. Python 3 error?

user4530588 picture user4530588 · Feb 18, 2015 · Viewed 421.7k 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].decode('utf-8')

at this point I get the error message

AttributeError: 'str' object has no attribute 'decode'

Python 3 doesn't have decode anymore, am I right? how can I fix this?

Also, in:

data = conn.fetch('1', '(BODY[HEADER])')

I am selecting only the 1st email. How do I select all?

Answer

Martijn Pieters picture Martijn Pieters · Feb 18, 2015

You are trying to decode an object that is already decoded. You have a str, there is no need to decode from UTF-8 anymore.

Simply drop the .decode('utf-8') part:

header_data = data[1][0][1]

As for your fetch() call, you are explicitly asking for just the first message. Use a range if you want to retrieve more messages. See the documentation:

The message_set options to commands below is a string specifying one or more messages to be acted upon. It may be a simple message number ('1'), a range of message numbers ('2:4'), or a group of non-contiguous ranges separated by commas ('1:3,6:9'). A range can contain an asterisk to indicate an infinite upper bound ('3:*').