TypeError序列项0:预期的str实例,找到的字节

时间:2019-05-17 02:26:30

标签: python email character-encoding imap imaplib

出于某种原因,我一直在此遇到TypeError

TypeError跟踪(最近一次通话) << / p>

ipython-input-19-3490eb36442d> in <module>
      2 result, numbers = mail.uid('search', None, "ALL")
      3 uids = numbers[0].split()
----> 4 result, messages = mail.uid('fetch', ','.join(uids), '(BODY[])')

mail.select("INBOX")
result, numbers = mail.uid('search', None, "ALL")
uids = numbers[0].split()
result, messages = mail.uid('fetch', ','.join(uids), '(BODY[])')
date_list = []
from_list = []
message_text = []
for _, message in messages[::2]:
    msg = email.message_from_string(message)
    if msg.is_multipart():
        t = []
    for p in msg.get_payload():
        t.append(p.get_payload(decode=True))
        message_text.append(t[0])

    else:message_text.append(msg.get_payload(decode=True))
    date_list.append(msg.get('date'))
    from_list.append(msg.get('from'))
    date_list = pd.to_datetime(date_list)
    print (len(message_text))
    print (len(from_list))
    df = pd.DataFrame(data={'Date':date_list,'Sender':from_list,'Message':message_text})
    print (df.head())
    df.to_csv('~inbox_email.csv',index=False)

1 个答案:

答案 0 :(得分:0)

此行

result, messages = mail.uid('fetch', ','.join(uids), '(BODY[])')

正在引发异常

  

TypeError序列项0:预期的str实例,找到的字节

检查行'fetch''(BODY[])'已经是字符串,因此它们不太可能成为问题。

剩下','.join(uids)uids实际上是bytes实例的列表,因此str.join引发了异常,因为它期望str实例的可迭代性。

要解决此问题,请先decode numbers[0]str进行操作。

result, numbers = mail.uid('search', None, "ALL")
uids = numbers[0].decode().split()    # <- decode before splitting
result, messages = mail.uid('fetch', ','.join(uids), '(BODY[])')