我在第18行(m = email.message_from_string(email_body))面临错误,说TypeError: initial_value must be str or None, not bytes
。当我尝试通过说print (data[0][1])
来运行它时,它以编码格式给出了电子邮件的输出。
我想调试错误。
import imaplib
import email
import os
svdir = 'C:\\Users\\rnandipati\\Downloads'
mail = imaplib.IMAP4_SSL('outlook.office365.com',993)
mail.login("rnaati@jess.com", "R!")
mail.select("Inbox")
typ, msgs = mail.search(None, '(SUBJECT "ADP Files")')
msgs = msgs[0].split()
for emailid in msgs:
resp, data = mail.fetch(emailid, "(RFC822)")
email_body = data[0][1]
m = email.message_from_string(email_body)
if m.get_content_maintype() != 'multipart':
continue
for part in m.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
if filename is not None:
sv_path = os.path.join(svdir, filename)
if not os.path.isfile(sv_path):
print(sv_path)
fp = open(sv_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
答案 0 :(得分:0)
email
模块包含一个函数message_from_bytes
。使用它而不是message_from_string
来解析bytes
对象。
m = email.message_from_bytes(email_body)