-_version = "2.1.0"
-__version__ = "$Revision$"[11:-2]
-__date__ = "$Date$"[7:-2]
-__revision__ = "$Id$"[5:-2]
-__author__ = "Oleg Broytmann <phd@phd.pp.ru>"
-__copyright__ = "Copyright (C) 2001-2006 PhiloSoft Design"
-__license__ = "GNU GPL"
+from mimedecode_version import __version__, __author__, __copyright__, __license__
-def output_headers(msg, outfile = sys.stdout):
- unix_from = msg.get_unixfrom()
- if unix_from:
- output(unix_from + os.linesep)
- for key, value in msg.items():
- output("%s: %s\n" % (key, value), outfile)
- output("\n", outfile) # End of headers
+def output_headers(msg, outfile=sys.stdout):
+ unix_from = msg.get_unixfrom()
+ if unix_from:
+ output(unix_from + '\n')
+ for key, value in msg.items():
+ output("%s: %s\n" % (key, value), outfile)
+ output("\n", outfile) # End of headers
- """Return a decoded string according to RFC 2047.
- NOTE: This is almost the same as email.Utils.decode.
- """
- from types import ListType
- import email.Header
-
- L = email.Header.decode_header(s)
- if not isinstance(L, ListType):
- # s wasn't decoded
- return s
-
- rtn = []
- for atom, charset in L:
- if charset is None:
- rtn.append(atom)
- else:
- rtn.append(recode2(atom, charset))
- rtn.append(' ')
- del rtn[-1] # remove the last space
-
- # Now that we've decoded everything, we just need to join all the parts
- # together into the final string.
- return ''.join(rtn)
+ """Return a decoded string according to RFC 2047.
+ NOTE: This is almost the same as email.Utils.decode.
+ """
+ from types import ListType
+ import email.Header
+
+ L = email.Header.decode_header(s)
+ if not isinstance(L, ListType):
+ # s wasn't decoded
+ return s
+
+ rtn = []
+ for atom, charset in L:
+ if charset is None:
+ rtn.append(atom)
+ else:
+ rtn.append(recode2(atom, charset))
+ rtn.append(' ')
+ del rtn[-1] # remove the last space
+
+ # Now that we've decoded everything, we just need to join all the parts
+ # together into the final string.
+ return ''.join(rtn)
- if msg.has_key(header):
- value = msg[header]
- new_value = _decode_header(value)
- if new_value <> value: # do not bother to touch msg if not changed
- set_header(msg, header, new_value)
+ if msg.has_key(header):
+ value = msg[header]
+ new_value = _decode_header(value)
+ if new_value <> value: # do not bother to touch msg if not changed
+ set_header(msg, header, new_value)
- if msg.has_key(header):
- value = msg.get_param(param, header=header)
- if value:
- from types import TupleType
- if isinstance(value, TupleType):
- new_value = _decode_header_param(value)
- else:
- new_value = _decode_header(value)
- if new_value <> value: # do not bother to touch msg if not changed
- msg.set_param(param, new_value, header)
+ if msg.has_key(header):
+ value = msg.get_param(param, header=header)
+ if value:
+ from types import TupleType
+ if isinstance(value, TupleType):
+ new_value = _decode_header_param(value)
+ else:
+ new_value = _decode_header(value)
+ if new_value <> value: # do not bother to touch msg if not changed
+ msg.set_param(param, new_value, header)
- for header, param in GlobalOptions.decode_header_params:
- decode_header_param(msg, header, param)
+ for header, param in GlobalOptions.decode_header_params:
+ decode_header_param(msg, header, param)
- entries = mailcap.lookup(caps, content_type, "view")
- for entry in entries:
- if entry.has_key('copiousoutput'):
- if entry.has_key('test'):
- test = mailcap.subst(entry['test'], content_type, filename)
- if test and os.system(test) != 0:
- continue
- command = mailcap.subst(entry["view"], content_type, filename)
- break
+ entries = mailcap.lookup(caps, content_type, "view")
+ for entry in entries:
+ if entry.has_key('copiousoutput'):
+ if entry.has_key('test'):
+ test = mailcap.subst(entry['test'], content_type, filename)
+ if test and os.system(test) != 0:
+ continue
+ command = mailcap.subst(entry["view"], content_type, filename)
+ break
- set_content_type(msg, "text/plain")
- msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
+ set_content_type(msg, "text/plain")
+ msg["X-MIME-Autoconverted"] = "from %s to text/plain by %s id %s" % (content_type, host_name, command.split()[0])
- save_charset = charset = msg.get_content_charset()
- if charset and charset <> GlobalOptions.default_charset:
- s = recode2(s, charset)
- content_type = msg.get_content_type()
- set_content_type(msg, content_type, GlobalOptions.default_charset)
- msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, GlobalOptions.default_charset, host_name, me)
- return s
+ save_charset = charset = msg.get_content_charset()
+ if charset and charset.lower() <> GlobalOptions.default_encoding:
+ s = recode2(s, charset)
+ content_type = msg.get_content_type()
+ set_content_type(msg, content_type, GlobalOptions.default_encoding)
+ msg["X-MIME-Autoconverted"] = "from %s to %s by %s id %s" % (save_charset, GlobalOptions.default_encoding, host_name, me)
+ return s
- # Decode body and recode charset
- s = decode_body(msg, instring)
- if GlobalOptions.recode_charset:
- s = recode_charset(msg, s)
+ # Decode body and recode charset
+ s = decode_body(msg, instring)
+ if GlobalOptions.recode_charset:
+ s = recode_charset(msg, s)
- "Decode one part of the message"
-
- decode_headers(msg)
- encoding = msg["Content-Transfer-Encoding"]
-
- if encoding in (None, '', '7bit', '8bit', 'binary'):
- outstring = str(msg.get_payload())
- else: # Decode from transfer ecoding to text or binary form
- outstring = str(msg.get_payload(decode=1))
- set_header(msg, "Content-Transfer-Encoding", "8bit")
- msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
-
- # Test all mask lists and find what to do with this content type
- masks = []
- ctype = msg.get_content_type()
- if ctype:
- masks.append(ctype)
- mtype = msg.get_content_maintype()
- if mtype:
- masks.append(mtype + '/*')
- masks.append('*/*')
-
- for content_type in masks:
- if content_type in GlobalOptions.totext_mask:
- totext(msg, outstring)
- return
- elif content_type in GlobalOptions.binary_mask:
- output_headers(msg)
- output(outstring)
- return
- elif content_type in GlobalOptions.ignore_mask:
- output_headers(msg)
- output("\nMessage body of type `%s' skipped.\n" % content_type)
- return
- elif content_type in GlobalOptions.error_mask:
- raise ValueError, "content type `%s' prohibited" % content_type
-
- # Neither content type nor masks were listed - decode by default
- totext(msg, outstring)
+ "Decode one part of the message"
+
+ decode_headers(msg)
+ encoding = msg["Content-Transfer-Encoding"]
+
+ if encoding in (None, '', '7bit', '8bit', 'binary'):
+ outstring = str(msg.get_payload())
+ else: # Decode from transfer ecoding to text or binary form
+ outstring = str(msg.get_payload(decode=1))
+ set_header(msg, "Content-Transfer-Encoding", "8bit")
+ msg["X-MIME-Autoconverted"] = "from %s to 8bit by %s id %s" % (encoding, host_name, me)
+
+ # Test all mask lists and find what to do with this content type
+ masks = []
+ ctype = msg.get_content_type()
+ if ctype:
+ masks.append(ctype)
+ mtype = msg.get_content_maintype()
+ if mtype:
+ masks.append(mtype + '/*')
+ masks.append('*/*')
+
+ for content_type in masks:
+ if content_type in GlobalOptions.totext_mask:
+ totext(msg, outstring)
+ return
+ elif content_type in GlobalOptions.binary_mask:
+ output_headers(msg)
+ output(outstring)
+ return
+ elif content_type in GlobalOptions.ignore_mask:
+ output_headers(msg)
+ output("\nMessage body of type `%s' skipped.\n" % content_type)
+ return
+ elif content_type in GlobalOptions.error_mask:
+ raise ValueError, "content type `%s' prohibited" % content_type
+
+ # Neither content type nor masks were listed - decode by default
+ totext(msg, outstring)
- if use_locale:
- # Get the default charset.
- try:
- lcAll = locale.setlocale(locale.LC_ALL, '').split('.')
- except locale.Error, err:
- print >> sys.stderr, "WARNING:", err
- lcAll = []
-
- if len(lcAll) == 2:
- default_charset = lcAll[1]
- else:
- try:
- default_charset = locale.getpreferredencoding()
- except locale.Error, err:
- print >> sys.stderr, "WARNING:", err
- default_charset = sys.getdefaultencoding()
- else:
- default_charset = sys.getdefaultencoding()
-
- recode_charset = 1 # recode charset of message body
-
- decode_headers = ["Subject", "From"] # A list of headers to decode
- decode_header_params = [("Content-Type", "name"),
- ("Content-Disposition", "filename")
- ] # A list of headers' parameters to decode
-
- totext_mask = [] # A list of content-types to decode
- binary_mask = [] # A list to pass through
- ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
- error_mask = [] # Raise error if encounter one of these
+ from m_lib.defenc import default_encoding
+ recode_charset = 1 # recode charset of message body
+
+ decode_headers = ["From", "Subject"] # A list of headers to decode
+ decode_header_params = [
+ ("Content-Type", "name"),
+ ("Content-Disposition", "filename"),
+ ] # A list of headers' parameters to decode
+
+ totext_mask = [] # A list of content-types to decode
+ binary_mask = [] # A list to pass through
+ ignore_mask = [] # Ignore (skip, do not decode and do not include into output)
+ error_mask = [] # Raise error if encounter one of these
- from getopt import getopt, GetoptError
-
- try:
- options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:',
- ['help', 'version'])
- except GetoptError:
- usage(1)
-
- for option, value in options:
- if option == '-h':
- usage()
- elif option == '--help':
- usage()
- elif option == '-V':
- version()
- elif option == '--version':
- version()
- elif option == '-c':
- GlobalOptions.recode_charset = 1
- elif option == '-C':
- GlobalOptions.recode_charset = 0
- elif option == '-f':
- GlobalOptions.default_charset = value
- elif option == '-d':
- GlobalOptions.decode_headers.append(value)
- elif option == '-D':
- GlobalOptions.decode_headers = []
- elif option == '-p':
- GlobalOptions.decode_header_params.append(value.split(':', 1))
- elif option == '-P':
- GlobalOptions.decode_header_params = []
- elif option == '-t':
- GlobalOptions.totext_mask.append(value)
- elif option == '-b':
- GlobalOptions.binary_mask.append(value)
- elif option == '-i':
- GlobalOptions.ignore_mask.append(value)
- elif option == '-e':
- GlobalOptions.error_mask.append(value)
- else:
- usage(1)
-
- return arguments
+ from getopt import getopt, GetoptError
+
+ try:
+ options, arguments = getopt(sys.argv[1:], 'hVcCDPf:d:p:b:e:i:t:',
+ ['help', 'version'])
+ except GetoptError:
+ usage(1)
+
+ for option, value in options:
+ if option == '-h':
+ usage()
+ elif option == '--help':
+ usage()
+ elif option == '-V':
+ version()
+ elif option == '--version':
+ version()
+ elif option == '-c':
+ GlobalOptions.recode_charset = 1
+ elif option == '-C':
+ GlobalOptions.recode_charset = 0
+ elif option == '-f':
+ GlobalOptions.default_encoding = value
+ elif option == '-d':
+ GlobalOptions.decode_headers.append(value)
+ elif option == '-D':
+ GlobalOptions.decode_headers = []
+ elif option == '-p':
+ GlobalOptions.decode_header_params.append(value.split(':', 1))
+ elif option == '-P':
+ GlobalOptions.decode_header_params = []
+ elif option == '-t':
+ GlobalOptions.totext_mask.append(value)
+ elif option == '-b':
+ GlobalOptions.binary_mask.append(value)
+ elif option == '-i':
+ GlobalOptions.ignore_mask.append(value)
+ elif option == '-e':
+ GlobalOptions.error_mask.append(value)
+ else:
+ usage(1)
+
+ return arguments