import sys, os
import email
-try:
- from cStringIO import StringIO
-except ImportError:
- from StringIO import StringIO
-
me = os.path.basename(sys.argv[0])
totext(msg, outstring)
-def decode_file(infile):
- "Decode the entire message"
-
- msg = email.message_from_file(infile)
+def decode_multipart(msg):
+ "Decode multipart"
if msg.is_multipart():
decode_headers(msg)
boundary = msg.get_boundary()
for subpart in msg.get_payload():
- output("\n--%s\n" % boundary)
+ if boundary:
+ output("\n--%s\n" % boundary)
- if subpart.is_multipart(): # Recursively decode all parts of the subpart
- newfile = StringIO(subpart.as_string())
- newfile.seek(0)
- decode_file(newfile)
- else:
- decode_part(subpart)
+ # Recursively decode all parts of the subpart
+ decode_message(subpart)
- output("\n--%s--\n" % boundary)
+ if boundary:
+ output("\n--%s--\n" % boundary)
if msg.epilogue:
output(msg.epilogue)
- else:
- if msg.has_key("Content-Type"): # Simple one-part message - decode it
- decode_part(msg)
+def decode_message(msg):
+ "Decode message"
- else: # Not a message, just text - copy it literally
- output(msg.as_string())
+ if msg.is_multipart():
+ decode_multipart(msg)
+ elif msg.has_key("Content-Type"): # Simple one-part message - decode it
+ decode_part(msg)
+ else: # Not a message, just text - copy it literally
+ output(msg.as_string())
class GlobalOptions:
output = outfile.write
try:
- decode_file(infile)
+ decode_message(email.message_from_file(infile))
finally:
infile.close()
outfile.close()