【发布时间】:2021-01-30 06:47:55
【问题描述】:
登录并阅读主题作品。读取正文时发生错误。错误是什么?在互联网上,错误总是在这部分:“email.message_from_bytes(data[0][1].decode())”但我认为这部分是正确的。
# Connection settings
HOST = 'imap.host'
USERNAME = 'name@domain.com'
PASSWORD = 'password'
m = imaplib.IMAP4_SSL(HOST, 993)
m.login(USERNAME, PASSWORD)
m.select('INBOX')
result, data = m.uid('search', None, "UNSEEN")
if result == 'OK':
for num in data[0].split()[:5]:
result, data = m.uid('fetch', num, '(RFC822)')
if result == 'OK':
email_message_raw = email.message_from_bytes(data[0][1])
email_from = str(make_header(decode_header(email_message_raw['From'])))
# von Edward Chapman -> https://stackoverflow.com/questions/7314942/python-imaplib-to-get-gmail-inbox-subjects-titles-and-sender-name
subject = str(email.header.make_header(email.header.decode_header(email_message_raw['Subject'])))
# content = email_message_raw.get_payload(decode=True)
# von Todor Minakov -> https://stackoverflow.com/questions/17874360/python-how-to-parse-the-body-from-a-raw-email-given-that-raw-email-does-not
b = email.message_from_string(email_message_raw)
body = ""
if b.is_multipart():
for part in b.walk():
ctype = part.get_content_type()
cdispo = str(part.get('Content-Disposition'))
# skip any text/plain (txt) attachments
if ctype == 'text/plain' and 'attachment' not in cdispo:
body = part.get_payload(decode=True) # decode
break
# not multipart - i.e. plain text, no attachments, keeping fingers crossed
else:
body = b.get_payload(decode=True)
m.close()
m.logout()
txt = body
regarding = subject
print("###########################################################")
print(regarding)
print("###########################################################")
print(txt)
print("###########################################################")
错误信息:
TypeError: initial_value 必须是 str 或 None,而不是 Message
感谢cmets的回复
【问题讨论】:
-
请发布堆栈跟踪
-
给定
email_message_raw = email.message_from_bytes(data[0][1]),email_message_raw是一个消息对象,然后您尝试在调用b = email.message_from_string(email_message_raw)时使用它,这需要一个搅拌。 -
我现在该怎么办?
标签: python python-3.x imap