#!/usr/bin/python import sys from email.message import Message, _unquotevalue import email.utils def de_comment(field): """Parse a header field fragment and remove comments. copied from AddrlistClass.getdelimited() in email/_parseaddr.py """ slist = [''] quote = False pos = 0 depth = 0 while pos < len(field): if quote: quote = False elif field[pos] == '(': depth += 1 elif field[pos] == ')': depth = max(depth - 1, 0) pos += 1 continue elif field[pos] == '\\': quote = True if depth == 0: slist.append(field[pos]) pos += 1 return ''.join(slist) ##################################################### # the rest shows a possible use of the above function def is_quoted(value): """ Check whether a value (string or tuple) is quoted """ if isinstance(value, tuple): return value[2].startswith('"') else: return value.startswith('"') class MyMessage(Message): """Email message with comments stripped """ def __init__(self, *args, **kwargs): Message.__init__(self, *args, **kwargs) def get_filename(self, failobj=None): """Return the filename associated with the payload if present. The filename is extracted from the Content-Disposition header's `filename' parameter. If that header is missing the `filename' parameter, this method falls back to looking for the `name' parameter. """ # changed from original: get the unquoted string missing = object() filename = self.get_param('filename', missing, 'content-disposition', unquote=False) if filename is missing: filename = self.get_param('name', missing, 'content-type', unquote=False) if filename is missing: return failobj # added to original: non quoted comments are removed bare = is_quoted(filename) if not bare: filename = _unquotevalue(filename) filename = email.utils.collapse_rfc2231_value(filename) if bare and '(' in filename: filename = de_comment(filename) return filename.strip() if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: attachments.py " sys.exit(0) msg = email.message_from_file(open(sys.argv[1]), _class=MyMessage) for part in msg.walk(): print part.get_filename()