'str' object has no attribute 'decode'. Python 3 error?
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?
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:*'
).
If you land here using jwt authentication after the PyJWT v2.0.0 release (22/12/2020), you might want to freeze your version of PyJWT to the previous release in your requirements.txt
file.
PyJWT==1.7.1
Begining with Python 3, all strings are unicode objects.
a = 'Happy New Year' # Python 3
b = unicode('Happy New Year') # Python 2
The instructions above are the same. So I think you should remove the .decode('utf-8')
part because you already have a unicode object.