【发布时间】:2018-07-04 20:44:20
【问题描述】:
每天早上都会收到一封包含 Excel 附件的电子邮件。我希望能够获取这些附件中的每一个并将它们保存到同一个文件夹中。我尝试了以下代码:
Downloading multiple attachments using imaplib
https://gist.github.com/jasonrdsouza/1674794
https://gist.github.com/baali/2633554
但我一直遇到同样的错误:
initial_value must be str or None, not bytes
我认为这是因为其中一封电子邮件/附件有问题,但我不确定如何排除故障。
代码:
detach_dir = 'C:/Users/myname'
m = imaplib.IMAP4_SSL("outlook.office365.com")
m.login('emailaddress@server.com','password')
m.select("INBOX")
resp, items = m.search(None, '(SUBJECT "Daily Report")')
items = items[0].split()
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_string(email_body)
#^This is where the error occurs
temp = m.store(emailid,'+FLAGS', '\\Seen')
m.expunge()
if mail.get_content_maintype() != 'multipart':
continue
#print "["+mail["From"]+"] :" + mail["Subject"]
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
att_path = os.path.join(detach_dir, filename)
if not os.path.isfile(att_path) :
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
这是错误:
TypeError Traceback (most recent call last)
<ipython-input-6-07c04531d5aa> in <module>()
5 resp, data = m.fetch(emailid, "(RFC822)")
6 email_body = data[0][1]
----> 7 mail = email.message_from_string(email_body)
8 #This is where the error occurs
9 temp = m.store(emailid,'+FLAGS', '\\Seen')
~\AppData\Local\Continuum\anaconda3\lib\email\__init__.py in message_from_string(s, *args, **kws)
36 """
37 from email.parser import Parser
---> 38 return Parser(*args, **kws).parsestr(s)
39
40 def message_from_bytes(s, *args, **kws):
~\AppData\Local\Continuum\anaconda3\lib\email\parser.py in parsestr(self, text, headersonly)
66 the file.
67 """
---> 68 return self.parse(StringIO(text), headersonly=headersonly)
69
70
TypeError: initial_value must be str or None, not bytes
当我针对不同的主题对其进行测试时,该代码运行良好,因此我假设有一封电子邮件或附件将其搞砸了。将搜索减少到 1 月 1 日以后发送的电子邮件可能会奏效,但我不知道如何操纵对两个参数的搜索:
typ, msgs = mails.search(None, '(SUBJECT "Daily Report")', 'SENTSINCE 01-JAN-2018')
【问题讨论】:
-
编辑了问题。
-
我对您的问题没有任何经验,但您的描述中明显遗漏了以下问题的答案:“每封电子邮件都会发生这种情况吗?每封带有附件的电子邮件都会发生这种情况吗?”
-
是的,我给自己发了两封电子邮件,附有不同主题的附件,脚本运行良好。我认为其中一封电子邮件/附件有问题...我只是尝试将搜索限制为自 1 月 1 日 typ 以来发送的附件,msgs = mails.search(None, '(SUBJECT "Daily Report")', 'SENTSINCE 01 -JAN-2018') 但我认为这不是这样做的方法......?
-
编辑到问题中。
-
Python2 还是 Python3?