fix: handle multipart MIME attachments in partition_email

Closed
AL
9mo ago
+136-3

Summary

  • Fixes #3922 — partition_email crashes with KeyError: 'multipart/mixed' when processing PGP-signed emails with process_attachments=True
  • Root cause: Python's email.contentmanager has no handler for multipart/* content types, so get_content() raises KeyError when called on a multipart MIME part that appears as an "attachment" (e.g. multipart/signed inside a multipart/mixed envelope)
  • Fix applied in three layers:
    • _file_bytes: check is_multipart() first and use as_bytes() for raw MIME bytes
    • _iter_elements: move file creation inside the try/except block for uniform error handling
    • EXPECTED_ATTACHMENT_ERRORS: add KeyError as safety net for unhandled content types

Files changed

  • unstructured/partition/email.py — _file_bytes multipart handling + _iter_elements error boundary fix
  • unstructured/partition/common/__init__.py — add KeyError to EXPECTED_ATTACHMENT_ERRORS
  • test_unstructured/partition/test_email.py — 2 new unit tests
  • example-docs/eml/mime-signed-multipart.eml — test fixture (simple PGP-signed email)
  • example-docs/eml/mime-signed-with-attachment.eml — test fixture (reproduces exact bug scenario)

Test plan

  • _file_bytes returns raw bytes for multipart attachments via as_bytes()
  • _file_bytes still works normally for regular (non-multipart) attachments
  • All 37 existing unit tests pass unchanged
  • ruff check and ruff format clean

🤖 Generated with Claude Code