'str' 对象没有属性 'decode'.Python 3 错误? [英] 'str' object has no attribute 'decode'. Python 3 error?

查看:154
本文介绍了'str' 对象没有属性 'decode'.Python 3 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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 没有解码了,对吗?我怎样才能解决这个问题?

Python 3 doesn't have decode anymore, am I right? how can I fix this?

此外,在:

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

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

I am selecting only the 1st email. How do I select all?

推荐答案

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

You are trying to decode an object that is already decoded. You have a str, there is no need to decode from UTF-8 anymore.

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

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

至于您的 fetch() 调用,您明确要求仅获取第一条消息.如果要检索更多消息,请使用范围.请参阅文档:

As for your fetch() call, you are explicitly asking for just the first message. Use a range if you want to retrieve more messages. See the documentation:

下面命令的 message_set 选项是一个字符串,指定要对其执行的一个或多个消息.它可能是一个简单的消息号('1')、一个消息号范围('2:4')或一组由逗号 ('1:3,6:9').一个范围可以包含一个星号来表示一个无限的上限 ('3:*').

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:*').

这篇关于'str' 对象没有属性 'decode'.Python 3 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆