python - 'str' 对象没有属性 'decode' 。 Python 3 错误?

标签 python python-3.x imaplib

这是我的代码:

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')

此时我收到错误消息

AttributeError: 'str' object has no attribute 'decode'

Python 3 不再具有解码功能,对吗?我怎样才能解决这个问题?

另外,在:

data = conn.fetch('1', '(BODY[HEADER])')

我只选择第一封电子邮件。如何全选?

最佳答案

您正在尝试解码一个已经解码的对象。你有一个 str,不需要再从 UTF-8 解码了。

只需删除 .decode('utf-8') 部分:

header_data = data[1][0][1]

至于您的 fetch() 调用,您明确要求只获取第一条消息。如果要检索更多消息,请使用范围。见 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:*').

关于python - 'str' 对象没有属性 'decode' 。 Python 3 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28583565/

相关文章:

python - TensorFlow 中 Tensor 的部分更新

python-2.7 - Python int 太大,无法在 python 3.4 中转换为 C long

python - 复制后如何唯一标识 IMAP 邮件?

python - imaplib.error : command SEARCH illegal in state AUTH, 只允许在已选择的状态下使用

python - 获取 "' NoneType' 对象没有属性 'items'“PIL 库错误

python - 如何显示用户的错误?

python - Intellij idea 无法识别 python 3 中本地类的导入

python - 如何使用 for 循环检查板中的所有值是否已满

python - 使用 Python 的 Gmail 中的 IMAP 问题

python - 让 Fabric Python 库工作