I have a script to read messages on a mail server and save them in specific folders based on the content of the message bodies. Intermittently, usually about once or twice a day, it fails while executing this part of the code:
if not os.path.isfile(att_path) :
# finally write the stuff
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
ext = att_path.split(".")[-1]
print "att_path",att_path
f = open(att_path.replace("."+ext,".txt"),'wb')
f.write(headers)
f.write("\n\n\n")
f.write(body)
f.close()
filelist.append(vdir+"/"+filename)
messageReceived = True
else:
noErrors = False
errFiles.append(vdir+"/"+filename)
It saves the actual attachment in the expected directory, but not the subsequent text file with the headers and body information. Because an exception is thrown ("[Errno 9] Bad file descriptor"), the email is not marked for deletion and stays on the server until the saved attachment is either deleted or moved, at which point both files will be saved without any errors.
I'm stumped at what could be causing it, since it processes several hundred emails every day without any problems, except for this intermittent issue.