Skip to content

fix: handle multipart MIME attachments in partition_email - #4277

Closed
AlonNaor22 wants to merge 1 commit into
Unstructured-IO:mainfrom
AlonNaor22:fix/email-multipart-attachment-keyerror
Closed

AlonNaor22 wants to merge 1 commit into
Unstructured-IO:mainfrom
AlonNaor22:fix/email-multipart-attachment-keyerror

Conversation

@AlonNaor22

Copy link
Copy Markdown

Summary

  • Fixes bug/partition_signed_emails #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

When a PGP-signed email is wrapped in a multipart/mixed envelope, the
multipart/signed part appears as an "attachment" via iter_attachments().
Calling get_content() on it raises KeyError because Python's
email.contentmanager has no handler for multipart content types.

Fix in three layers:
- _file_bytes: check is_multipart() first and use as_bytes() to get raw
  MIME bytes instead of calling get_content() which cannot handle
  multipart types
- _iter_elements: move file creation inside the try/except block so all
  attachment processing errors go through the same error handler
- EXPECTED_ATTACHMENT_ERRORS: add KeyError as a safety net for any
  remaining unhandled content types from the content manager

Closes #3922

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@AlonNaor22 AlonNaor22 closed this by deleting the head repository Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug/partition_signed_emails

1 participant