Trouble isolating emails when downloading via Python script -
i have script fetches emails account, downloads attachments, creates html email blast program, , zips them nice little archive. works when 1 email present in inbox, however, script hangs when multiple emails exist. feel because section of script zips files not looping correctly. trying accomplish 1 zip file each email. 3 emails in inbox = 3 seperate zip files. i've done best reduce code maximum readability while still maintaining core structure. point me in right direction here? thanks!
code:
for emailid in items: resp, data = m.fetch(emailid, "(rfc822)") email_body = data[0][1] mail = email.message_from_string(email_body) part in mail.walk(): if part.get_content_type() == 'text/plain': content = part.get_payload() #do something/define variables email contents if mail.get_content_maintype() != 'multipart': continue part in mail.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('content-disposition') 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) 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 f in os.listdir('.')] file in allfiles: archive = zipfile.zipfile(token+'.zip', mode='a') archive.write(file) archive.close() os.unlink(file)
update
here alink complete code. http://ideone.com/wexv9p
there seems mistake here:
counter = 1 if not filename: filename = 'part-%03d%s' % (counter, 'bin') counter += 1
counter 1 in loop, want define before second
for part in mail.walk():
edit:
okay, think problem @ last part of code
allfiles = [f f in os.listdir('.')] file in allfiles: archive = zipfile.zipfile(token+'.zip', mode='a') archive.write(file) archive.close() os.unlink(file)
this create zip file each part of email
i think want indent out level , change more this:
allfiles = [f f in os.listdir(detach_dir) if not f.endswith(".zip")] file in allfiles: archive = zipfile.zipfile(token+'.zip', mode='a') archive.write(file) archive.close() os.unlink(file)
that way won't recursively zip other zip files or remove them
Comments
Post a Comment