How to read eml file in python?

前端 未结 4 1514
滥情空心
滥情空心 2021-01-31 12:37

I do not known how to load a eml file in python 3.4.
I want to list all and read all of them in python.

\"ente

4条回答
  •  渐次进展
    2021-01-31 13:09

    Try this:

    #!python3
    # -*- coding: utf-8 -*-
    
    import email
    import os
    
    SOURCE_DIR = 'email'
    DEST_DIR = 'temp'
    
    def extractattachements(fle,suffix=None):
        message = email.message_from_file(open(fle))
        filenames = []
        if message.get_content_maintype() == 'multipart':
            for part in message.walk():
                if part.get_content_maintype() == 'multipart': continue
                #if part.get('Content-Disposition') is None: continue
                if part.get('Content-Type').find('application/octet-stream') == -1: continue
                filename = part.get_filename()
                if suffix:
                    filename = ''.join( [filename.split('.')[0], '_', suffix, '.', filename.split('.')[1]])
                filename = os.path.join(DEST_DIR, filename)
                fb = open(filename,'wb')
                fb.write(part.get_payload(decode=True))
                fb.close()
                filenames.append(filename)
        return filenames
    
    def main():
        onlyfiles = [f for f in os.listdir(SOURCE_DIR) if os.path.isfile(os.path.join(SOURCE_DIR, f))]
        for file in onlyfiles:
            #print path.join(SOURCE_DIR,file)
            extractattachements(os.path.join(SOURCE_DIR,file))
        return True
    
    if __name__ == "__main__":
        main()
    

提交回复
热议问题