【问题标题】:TypeError: initial_value must be str or none, not bytes in python 3?TypeError:initial_value 必须是 str 或 none,而不是 python 3 中的字节?
【发布时间】:2015-04-19 12:51:07
【问题描述】:

这是我的代码:

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]
parser = HeaderParser()
msg = parser.parsestr(header_data)

从这里我得到错误信息:

TypeError: initial_value must be str or none, not bytes

我正在使用显然会自动解码的 python 3。那么为什么我仍然收到此错误消息?

【问题讨论】:

  • 您在哪一行收到该错误?
  • msg = parser.parsestr(header_data)

标签: python python-3.x imaplib


【解决方案1】:

你可以试试:

header_data = data[1][0][1].decode('utf-8')

【讨论】:

  • 这行得通,谢谢。使用 Python 2,您不需要使用 decode()
【解决方案2】:

我建议这样做,(Python 3)

typ, data = conn.fetch('1', '(RFC822)') # will read the first email
email_content = data[0][1] 
msg = email.message_from_bytes(email_content) # this needs to be corrected in your case 
emailDate =  msg["Date"]
emaiSubject = msg["Subject"]

【讨论】:

    【解决方案3】:

    在这种情况下,您可能希望使用BytesHeaderParser

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-25
      • 2023-03-09
      • 1970-01-01
      • 2018-09-13
      • 2018-04-12
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多