我有一个脚本,可以从我的帐户中获取电子邮件、下载附件、为电子邮件爆炸程序创建一些 html,然后将它们压缩到一个不错的小存档中。当收件箱中只有一封电子邮件时,这很有效,但是,当存在多封电子邮件时,脚本会挂起。我觉得这是因为压缩文件的脚本部分没有正确循环。我想要完成的是每封电子邮件的一个 zip 文件。收件箱中的 3 封电子邮件 = 3 个单独的 zip 文件。我已尽最大努力减少代码以获得最大的可读性,同时仍保持核心结构。谁能在这里指出我正确的方向?谢谢!
代码:
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_string(email_body)
for part in mail.walk():
if part.get_content_type() == 'text/plain':
content = part.get_payload()
#do something/define variables from email contents
if mail.get_content_maintype() != 'multipart':
continue
for part in mail.walk():
if part.get_content_maintype() == 'multipart':
continue
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
counter = 1
if not filename:
filename = 'part-%03d%s' % (counter, 'bin')
counter += 1
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()
path = 'C:\directory'
os.chdir(path)
for file in os.listdir('.'):
#download attachments
htmlFile = str(token)+'.html'
htmlCode = ('<html>HTML goes here</html>')
htmlData = open(os.path.join('C:\directory', htmlFile), 'w+')
htmlData.write(htmlCode)
print htmlFile+' Complete'
htmlData.close()
allFiles = [f for f in os.listdir('.')]
for file in allFiles:
archive = zipfile.ZipFile(token+'.zip', mode='a')
archive.write(file)
archive.close()
os.unlink(file)
更新
这是完整代码的链接。http://ideone.com/WEXv9P