|
5 | 5 |
|
6 | 6 | from __future__ import annotations |
7 | 7 |
|
| 8 | +import copy |
8 | 9 | import datetime as dt |
9 | 10 | import email |
10 | 11 | import email.policy |
@@ -438,10 +439,36 @@ def _attachment_file_name(self) -> str | None: |
438 | 439 | @cached_property |
439 | 440 | def _file_bytes(self) -> bytes: |
440 | 441 | """The bytes of the attached file.""" |
| 442 | + # -- `email.contentmanager` has no `get_content()` handler registered for any |
| 443 | + # -- `multipart/*` content-type (handlers exist for text/*, application/*, image/*, |
| 444 | + # -- message/rfc822, etc., but multipart sub-parts are normally consumed via |
| 445 | + # -- `.iter_parts()`, not `.get_content()`). A multipart sub-part can still appear as an |
| 446 | + # -- "attachment" though, e.g. a PGP/MIME-signed forwarded message (`multipart/signed`) |
| 447 | + # -- nested inside a `multipart/mixed` envelope. Fall back to the part's raw serialized |
| 448 | + # -- bytes in that case rather than letting `get_content()` raise `KeyError`. |
| 449 | + if self._attachment.get_content_type().startswith("multipart/"): |
| 450 | + return self._serialized_multipart_bytes |
| 451 | + |
441 | 452 | content = self._attachment.get_content() |
442 | 453 |
|
443 | 454 | if isinstance(content, str): |
444 | 455 | return content.encode("utf-8") |
445 | 456 |
|
446 | 457 | assert isinstance(content, bytes) |
447 | 458 | return content |
| 459 | + |
| 460 | + @cached_property |
| 461 | + def _serialized_multipart_bytes(self) -> bytes: |
| 462 | + """Raw serialized bytes of a `multipart/*` attachment, re-parseable as a document. |
| 463 | +
|
| 464 | + `EmailMessage.get_body()` skips any candidate part -- including a `multipart/*` root |
| 465 | + message -- whose own `Content-Disposition` is "attachment". This MIME part carries |
| 466 | + exactly that header (that's how it surfaced as an attachment via `iter_attachments()` |
| 467 | + in the first place), so serializing it verbatim and re-parsing it as the root of a new |
| 468 | + message would make `partition_email()` find no body at all. Strip that header on a |
| 469 | + *copy* before serializing -- `self._attachment` itself is left untouched since |
| 470 | + `_attachment_file_name` still needs its original `Content-Disposition` filename param. |
| 471 | + """ |
| 472 | + part = copy.deepcopy(self._attachment) |
| 473 | + del part["Content-Disposition"] |
| 474 | + return part.as_bytes() |
0 commit comments