Python IMAP: =?utf-8?Q? in subject string

2019-02-16 11:05发布

I am displaying new email with IMAP, and everything looks fine, except for one message subject shows as:

=?utf-8?Q?Subject?=

How can I fix it?

3条回答
爷的心禁止访问
2楼-- · 2019-02-16 11:50

Try Imbox

Because imaplib is a very excessive low level library and returns results which are hard to work with

Installation

pip install imbox

Usage

from imbox import Imbox

with Imbox('imap.gmail.com',
        username='username',
        password='password',
        ssl=True,
        ssl_context=None,
        starttls=False) as imbox:

    all_inbox_messages = imbox.messages()
    for uid, message in all_inbox_messages:
        message.subject
查看更多
姐就是有狂的资本
3楼-- · 2019-02-16 12:01

This is a MIME encoded-word. You can parse it with email.header:

import email.header

def decode_mime_words(s):
    return u''.join(
        word.decode(encoding or 'utf8') if isinstance(word, bytes) else word
        for word, encoding in email.header.decode_header(s))

print(decode_mime_words(u'=?utf-8?Q?Subject=c3=a4?=X=?utf-8?Q?=c3=bc?='))
查看更多
劫难
4楼-- · 2019-02-16 12:08

In MIME terminology, those encoded chunks are called encoded-words. You can decode them like this:

import email.Header
text, encoding = email.Header.decode_header('=?utf-8?Q?Subject?=')[0]

Check out the docs for email.Header for more details.

查看更多
登录 后发表回答