如何使用Python 3.x从电子邮件附件下载excel文件(.xlsx)

时间:2018-01-11 23:44:58

标签: python-3.x email imap

一天中的这个时候再也没有头发!整个上午花了一些机器人来监控我的电子邮件并下载excel电子邮件附件,并根据该电子邮件中找到的关键字主题行运行单独的脚本。到目前为止,我把所有东西放在一起并运作良好....除了......文件没有被正确下载和存储。当我打开它时,我收到无效或损坏的文件错误(img如下):

enter image description here

此外,由于文件大小= 0kb

,文件肯定无法正确复制

代码是:

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)

我知道这不需要说,但是会对如何解决这个问题而不是立即给出答案表示赞赏。 (我喜欢把自己的头发拉出XD)。

对于让我这么远的其他问题的一些答案只是大喊大叫。这完全不是我的工作,因为电子邮件包对我来说是完全陌生的,文档有点粗略要遵循!

Helped out so far!

编辑:是os的utils中的xlsxwriter?我再盯着这个问题几个小时,安装了xlsxwriter包,看看我是否可以使用fp对象,但之后没有更改我的代码就可以了吗?如果有人可以告诉我这是愚蠢的,请告诉我,以便我可以将此问题标记为删除= D

0 个答案:

没有答案