96

Here is my code:

import imaplib
from email.parser import HeaderParser

conn = imaplib.IMAP4_SSL('imap.gmail.com')
conn.login('example@gmail.com', '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?

95

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:*').

  • 2
    Is there a simple way to do this conditionally? (I only want to decode if the message is encoded.) – devinbost Mar 21 at 20:56
  • 2
    @devinbost: in Python 3? Test for the object type or the decode attribute, or just catch the exception. try: data = data.decode('...') except AttributeError: pass. – Martijn Pieters Mar 22 at 7:46
  • 1
    @devinbost: however, you are usually better off decoding closer to the source of your data, where you'll usually know exactly what you have. – Martijn Pieters Mar 22 at 7:46
-1

It s already decoded in Python3, Try directly it should work.

1

I'm not familiar with the library, but if your problem is that you don't want a byte array, one easy way is to specify an encoding type straight in a cast:

>>> my_byte_str
b'Hello World'

>>> str(my_byte_str, 'utf-8')
'Hello World'
  • They don’t have a bytes object to begin with, and str(bytes_object, codec) is just an alternative spelling for bytes_object.decode(codec). Both fail if you really have a str instead. – Martijn Pieters Feb 9 at 10:12
  • You're right, this specific question does have a str already. This answer could still be useful to people in the future that may have byte arrays (this was the issue I faced when I originally stumbled upon this post). – Broper Feb 27 at 17:06
  • I'm not sure how you stumbled on this post, however, because my_byte_str.decode exists and works, and will not throw the exception in the question. – Martijn Pieters Feb 28 at 8:29
12

Use it by this Method:

str.encode().decode()
  • bytearray(str, 'encoding').decode('another_encoding') would do the job if you need to decode idna or any other encoding – Alex Jul 11 '17 at 10:41
  • 4
    This is useless. You are encoding to UTF-8, then decoding the resulting bytes as UTF-8, ending up where you started. You are keeping the CPU warm with no other benefit. – Martijn Pieters Feb 9 at 10:10
  • @MartijnPieters "ending up where you started" - not if you have escape sequences in your string, for example: >>> '\u0159'.encode().decode() 'ř' – Peter Mar 21 at 15:47
  • @Peter: no, you don't need encoding or decoding for that. '\u0159' prints the exact same output. You are confusing the string literal syntax with the canonical representation of the value. – Martijn Pieters Mar 21 at 16:25
  • 1
    You can directly use, There is no need to encode and then decode again. – Aditya Jul 11 at 5:32
20

Begin with Python 3, all string is unicode object.

  a = 'Happy New Year' # Python 3
  b = unicode('Happy New Year') # Python 2

the code before are same. So I think you should remove the .decode('utf-8'). Because you have already get the unicode object.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.