2

No longer have any hair by this time of the day! Spent all morning putting a bit of a bot together to monitor my email and download excel email attachments and run a separate script based upon a keyword subject line found in that email. I've so far put everything together and works well.... except.... the file is not being downloaded and stored correctly. When I go to open it, I get an invalid or corrupt file error (img below):

enter image description here

Additionally, the file definitely doesn't copy over correctly because file size= 0kb

Code is:

server=imaplib.IMAP4_SSL('outlook.office365.com')
server.login(usr,pw)
server.select(readonly=True)  """still testing code so I don't need to keep 
resetting message as unread"""
status,messages=server.search(None,'UNSEEN') 

for uid in messages[0].split():
    status,data=server.fetch(uid,'(RFC822)')
    body=data[0][1]
    dbody=body.decode()
    mail=email.message_from_string(dbody)

    if mail['SUBJECT'] == 'hey':  #temporary keyword TBD
        for i in mail.walk():
            if i.get_content_maintype()=='multipart':
                continue
            if i.get('Content-Disposition') is None:
                continue
            file=i.get_filename()
            att_path=os.path.join(file_dest,file)

            if not os.path.isfile(att_path):
                fp=open(att_path,'wb')
                fp.write(i.get_payload(decode=True))
                fp.close()
            print(att_path)

I know this doesn't need to be said, but would appreciate a bit of direction towards how to solve this issue rather than giving the answer right away. (I enjoy pulling my own hair out XD).

Just a shout out to some of the answers to other questions that got me this far. This is totally not my work, as the email package is totally foreign to me, and the documentation is a little rough to follow!

Helped out so far!

edit: is xlsxwriter in the utils of os? I stared at this issue for a few more hours, installed the xlsxwriter package to see if I can play with the fp object, but afterwards without changing my code it works now? If anyone can tell me that is stupid, let me know so I can flag this Question to be deleted =D

0 Answers0