Handling invalid zip files
[dmarc.git] / dmarc_to_database.py
index 272998f8ccce56e494c949fcca7017fe4fb96251..4bb2049cfc3e686d8c42fb927146f1ba010b7e3d 100644 (file)
@@ -14,10 +14,13 @@ def fetch_msg(num):
     return mailbox.uid('FETCH', num, '(RFC822)')[1][0][1]
 
 def xml_of_part(part):
-    with zipfile.ZipFile(io.BytesIO(part.get_payload(decode=True))) as zf:
-        fn = zf.infolist()[0].filename
-        contents = zf.read(fn).decode('utf-8')
-        return xml.etree.ElementTree.fromstring(contents)
+    try:
+        with zipfile.ZipFile(io.BytesIO(part.get_payload(decode=True))) as zf:
+            fn = zf.infolist()[0].filename
+            contents = zf.read(fn).decode('utf-8')
+            return xml.etree.ElementTree.fromstring(contents)
+    except zipfile.BadZipFile:
+        return None
 
 
 def xml_of(message):
@@ -183,7 +186,8 @@ resp, nums = mailbox.uid('SEARCH', None, mails_from)
 
 
 dmarc_reports = [report for report_set in [extract_report(fetch_msg(n)) for n in nums[0].split()]
-                for report in report_set]
+                for report in report_set
+                if report]
 
 mailbox.close()
 mailbox.logout()