]> git.phdru.name Git - mimedecode.git/blobdiff - mimedecode/mimedecode.py
Version 3.2.0: Copy `mailcap.py` from Python 3.12
[mimedecode.git] / mimedecode / mimedecode.py
index 4ca2f25d2d061dba16294d67ab8018ea00be2b37..c5c80b0185524cbcde9ca47d1ee8e1d52794021d 100644 (file)
@@ -1,6 +1,7 @@
 """Decode MIME message"""
 
 import os
+import shutil
 import subprocess
 import sys
 
@@ -215,7 +216,10 @@ caps = None  # Globally stored mailcap database; initialized only if needed
 def decode_body(msg, s):
     "Decode body to plain text using first copiousoutput filter from mailcap"
 
-    import mailcap
+    try:
+        import mailcap
+    except ImportError:  # Python 3.13
+        from mimedecode import mailcap_312 as mailcap
     import tempfile
 
     global caps
@@ -227,29 +231,28 @@ def decode_body(msg, s):
         charset = msg.get_content_charset()
     else:
         charset = None
-    filename = tempfile.mktemp()
+    tmpfile = tempfile.NamedTemporaryFile()
     command = None
 
     entries = mailcap.lookup(caps, content_type, "view")
     for entry in entries:
         if 'copiousoutput' in entry:
             if 'test' in entry:
-                test = mailcap.subst(entry['test'], content_type, filename)
+                test = mailcap.subst(entry['test'], content_type, tmpfile.name)
                 if test and os.system(test) != 0:
                     continue
-            command = mailcap.subst(entry["view"], content_type, filename)
+            command = mailcap.subst(entry["view"], content_type, tmpfile.name)
             break
 
     if not command:
         return s
 
-    outfile = open(filename, 'wb')
     if charset and bytes is not str and isinstance(s, bytes):  # Python3
         s = s.decode(charset, "replace")
     if not isinstance(s, bytes):
         s = s.encode(g.default_encoding, "replace")
-    outfile.write(s)
-    outfile.close()
+    tmpfile.write(s)
+    tmpfile.flush()
 
     pipe = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
     new_s = pipe.stdout.read()
@@ -268,7 +271,7 @@ def decode_body(msg, s):
         msg["X-MIME-Autoconverted"] = \
             "failed conversion from %s to text/plain by %s id %s" \
             % (content_type, g.host_name, command.split()[0])
-    os.remove(filename)
+    tmpfile.close()  # Will be removed on close
 
     return s
 
@@ -529,4 +532,5 @@ def open_output_file(filename):
         return open(fullpath, 'wb')
     except Exception:
         if create:
-            os.removedirs(full_dir)
+            shutil.rmtree(full_dir)
+        raise