19

我正在显示带有 的新电子邮件IMAP,一切看起来都很好,除了一个邮件主题显示为:

=?utf-8?Q?Subject?=

我该如何解决?

4

6 回答 6

31

在 MIME 术语中,这些编码块称为编码字。你可以像这样解码它们:

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

查看文档以email.header获取更多详细信息。

于 2012-10-15T21:22:32.157 回答
13

这是一个 MIME编码字。您可以使用以下方式解析它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?='))
于 2016-04-19T10:47:43.993 回答
7

在 Python 3.3+ 中,如果参数设置为,则email.parser中的解析类和函数会自动解码标题中的“编码词”policypolicy.default

>>> import email
>>> from email import policy

>>> msg = email.message_from_file(open('message.txt'), policy=policy.default)
>>> msg['from']
'Pepé Le Pew <pepe@example.com>'

解析类和函数有:

令人困惑的是,至少在 Python 3.8 之前,这些解析函数的默认策略是 not policy.default, but policy.compat32,它不会解码“编码词”。

>>> msg = email.message_from_file(open('message.txt'))
>>> msg['from']
'=?utf-8?q?Pep=C3=A9?= Le Pew <pepe@example.com>'
于 2019-03-17T17:49:12.110 回答
5

试用收件箱

因为imaplib是一个非常多的低级库并返回难以处理的结果

安装

pip install imbox

用法

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
于 2018-09-30T21:11:54.520 回答
1

在 Python 3 中,将其解码为近似字符串非常简单:

from email.header import decode_header, make_header

decoded = str(make_header(decode_header("=?utf-8?Q?Subject?=")))

decode_header请参阅和的文档make_header

于 2020-12-28T08:46:13.993 回答
0

高级 IMAP 库在这里可能有用:imap_tools

from imap_tools import MailBox, AND

# get list of email subjects from INBOX folder
with MailBox('imap.mail.com').login('test@mail.com', 'pwd', 'INBOX') as mailbox:
    subjects = [msg.subject for msg in mailbox.fetch()]
  • 解析的电子邮件属性
  • 用于搜索电子邮件的查询生成器
  • 电子邮件操作:复制、删除、标记、移动、查看
  • 文件夹操作:列表、设置、获取、创建、存在、重命名、删除、状态
  • 无依赖
于 2020-04-10T17:45:59.600 回答