IMAP Fetch Encoding

2020-07-25 09:33发布

问题:

I'm trying to fetch some email info from gmail using imap like this

"(BODY.PEEK[HEADER.FIELDS (subject from date)] X-GM-MSGID X-GM-LABELS X-GM-THRID)"

The problem is that it doesn't work well with special and accented characters. For example,

Stéphane Maniaci

is rendered as

=?ISO-8859-1?Q?St=E9phane_Maniaci?=

How do I tell Gmail to return the strings with an encoding of my choice, say I want Charset to be UTF-8.

How to adjust that in the IMAP command I mentioned above?

回答1:

Okay. I found out that email.utils can help out a lot here.

It has methods to parse date, emails, and any other information from imap messages.

It also has methods to decode imap strings. Like this

from email.header import decode_header
value, charset = decode_header(string_to_be_decoded)