Stack Exchange
Python imaplib: Display non-ASCII characters correctly
I am using Python 3.5 and imaplib to fetch an e-mail from GMail and print its body. The body contains non-ASCII characters.
These are 'encoded' in a strange way and I cannot find out how to fix this.
import email
import imaplib

c = imaplib.IMAP4_SSL('imap.gmail.com')
c.login('example@gmail.com', 'password')

c.select('Inbox')
_, data = c.fetch(b'12345', '(RFC822)')

mail = data[0][1]
message = email.message_from_bytes(mail)
payload = message.get_payload()

body = mail[0].as_string()
print(body)

Gives
>> ... Mit freundlichen Gr=C3=BC=C3=9Fen ...

instead of the desired
>> ... Mit freundlichen Grüßen ...

It looks to me like this is not an issue of encoding but one of conversion. But how do I tell Python to convert the characters correctly? Is there a more convenient library?

Possible duplicate of python email encoding problem

If you're using python3.6 or later you can use EmailMessage.get_content() to decode quoted-printable text automatically.  See my answer to the duplicate target question.

The text is encoded with quoted-printable encoding, which is a way to encode non-ascii characters in ascii text.  You can decode it using python's quopri module.
>>> import quopri
>>> bs = b'Gr=C3=BC=C3=9Fen'

>>> # Decode quoted-printable to raw bytes.
>>> utf8 = quopri.decodestring(bs)

>>> # Decode bytes to text.
>>> s = utf8.decode('utf-8')
>>> print(s)
Grüßen

You may find that quoted-printable is the value of the email's content-transfer-encoding header.

Python should already be decoding this when you get the payload, though. Perhaps it was double-encoded by the sender?

Adding a sample of the message (ideally, reduced to just a few lines, enough to see the essential headers and a line of encoded text) would help us conclusively debug this.

@tripleee in 3.6+ EmailMessage.get_content() will decode quoted-printable automatically - I added an answer to your dupe target.
