title: How to download excel file (.xlsx) from email attachment with Python 3.x
body: <p>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):  </p>
  
  <p><a href="https://i.stack.imgur.com/fF9pN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fF9pN.png" alt="enter image description here"></a></p>
  
  <p>Additionally, the file definitely doesn't copy over correctly because file size= 0kb</p>
  
  <p>Code is:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>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).</p>
  
  <p>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!</p>
  
  <p><a href="https://stackoverflow.com/questions/6225763/downloading-multiple-attachments-using-imaplib">Helped out so far!</a></p>
  
  <p><strong>edit:</strong>  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</p>