How to get a list of files from the archive (rar or zip) attached to the E-mail using Python?

StackOverflow https://stackoverflow.com/questions/17355073

  •  01-06-2022
  •  | 
  •  

سؤال

How to get a list of files from the archive (rar or zip) attached to the E-mail using Python? That is, I have a EML file. I do not need to unzip the files just to get a list. Theoretically possible option when attached very large file and process the extracted attachments can take a lot of time and resources.

هل كانت مفيدة؟

المحلول

Here's how to do that with the stdlib, getting the first attachment in a simple multi-part message stored as message.eml:

import email.parser
import StringIO
import zipfile

with open('message.eml') as f:
    msg = email.parser.Parser().parse(f)
attachment = msg.get_payload(1)
zipf = StringIO.StringIO(attachment.get_payload())
zip = zipfile.ZipFile(zipf)
filenames = zip.namelist()

This will parse the whole MIME envelope, decode the whole attachment, and read the ZIP directory of that attachment… but at least it won't uncompress any of the files in the ZIP archive, so I suspect you won't actually have any performance problem to worry about.

نصائح أخرى

This answer tells you how to get the file object (for a zip archive, use the ZipFile constructor to open the file, rather than the normal open() function). Then you can use zipfile.namelist() to get the names of the archive members

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top