【发布时间】:2019-10-03 15:38:33
【问题描述】:
我正在使用 imaplib 提取电子邮件,并且必须从中提取文本。
我的消息是多部分的,所以
typ , data = account.fetch(msg_uid , '(RFC822)')
raw_email = data[0][1]
msg = email.message_from_bytes(raw_email)
payload_msg = get_message(msg)
def get_message(message):
'''
This function returns an decoded body text of a message, depending on multipart\* or text\*
:param message: message content of an email
:return: body of email message
'''
body = None
if message.is_multipart():
print(str(message.get_content_type()) + ' is the message content type')
for part in message.walk():
cdispo = str(part.get('Content-Disposition'))
if part.is_multipart():
for subpart in part.walk():
cdispo = str(subpart.get('Content-Disposition'))
if subpart.get_content_type() == 'text/plain' and 'attachment' not in cdispo:
body = subpart.get_payload(decode=True)
elif subpart.get_content_type() == 'text/html':
body = subpart.get_payload(decode=True)
elif part.get_content_type() == 'text/plain' and 'attachment' not in cdispo:
body = part.get_payload(decode=True)
elif part.get_content_type() == 'text/html' and 'attachment' not in cdispo:
body = part.get_payload(decode=True)
elif message.get_content_type() == 'text/plain':
body = message.get_payload(decode=True)
elif message.get_content_type() == 'text/html':
body = message.get_payload(decode=True)
return body
现在,如果您看到上面的代码,msg 是我们正在获取并将其传递给 get_payload 方法的内容,其中 decode = True。但是当我获取正文并检查类型时,它仍然以字节为单位!为什么?
难道不是要转成字符串吗,奇怪的是我给decode=False的时候,是字符串格式的!我在这里做错了什么?我预计这里会出现相反的情况!
P.S : raw_email 在这里是字节,而 msg 在这里是一些 email.message 类型!
【问题讨论】:
标签: python-3.x encoding utf-8 decoding