docling-project/docling · error · DocumentLoadError

Could not initialize email backend for file with hash {self.

Error message

Could not initialize email backend for file with hash {self.document_hash}.

What it means

EmailDocumentBackend.__init__ wraps any non-ImportError exception raised while reading the input and parsing it with mailparser.parse_from_bytes() into DocumentLoadError. Common causes are malformed RFC 822 content, undecodable headers/bodies, or unreadable files; the true cause is chained as __cause__.

Source

Thrown at docling/backend/email_backend.py:102

        super().__init__(in_doc, path_or_stream, options)

        self.options: EmailBackendOptions = options
        self.valid = False
        self.is_msg = False
        self.mail: mailparser.MailParser | None = None

        try:
            raw = self._read_bytes()
            self.is_msg = raw.startswith(_MSG_MAGIC)
            if self.is_msg:
                raw = self._msg_to_rfc822_bytes(raw)
            self.mail = mailparser.parse_from_bytes(raw)

            self.valid = self.mail is not None
        except ImportError:
            raise
        except Exception as exc:
            raise DocumentLoadError(
                f"Could not initialize email backend for file with hash {self.document_hash}."
            ) from exc

    def _read_bytes(self) -> bytes:
        if isinstance(self.path_or_stream, BytesIO):
            return self.path_or_stream.getvalue()
        if isinstance(self.path_or_stream, Path):
            return self.path_or_stream.read_bytes()
        raise TypeError(f"Unsupported input type: {type(self.path_or_stream)}")

    @staticmethod
    def _header_safe(value: str) -> str:
        # Email header values must be single-line; collapse CR/LF to spaces so a
        # crafted .msg cannot inject headers and EmailMessage does not reject it.
        return value.replace("\r", " ").replace("\n", " ").strip()

    @staticmethod
    def _msg_to_rfc822_bytes(data: bytes) -> bytes:

View on GitHub (pinned to 61d76f1ff3)

Solutions

  1. Inspect exc.__cause__ on the DocumentLoadError to find the underlying mailparser error
  2. Verify the file is a real email (starts with headers like 'From:'/'Received:') before conversion
  3. Open the .eml in a mail client or Python email.parser to confirm it parses standalone
  4. Quarantine unparseable files and continue batch processing instead of aborting the run

Example fix

# before
res = converter.convert(email_path)  # crashes the batch on one bad file

# after
try:
    res = converter.convert(email_path)
except DocumentLoadError as exc:
    log.warning('skipping %s: %s', email_path, exc.__cause__ or exc)
    continue
Defensive patterns

Strategy: try-catch

Validate before calling

raw = Path(email_path).read_bytes()
head = raw[:512].lstrip().lower()
if not (head.startswith(b'from ') or head.startswith(b'received:') or head.startswith(b'return-path')):
    raise ValueError(f'{email_path} does not look like an RFC 822 message')

Try / catch

try:
    result = converter.convert(email_path)
except DocumentLoadError as exc:
    log.warning('unparseable email %s: %s', email_path, exc.__cause__ or exc)
    quarantine(email_path)

Prevention

When it happens

Trigger: Passing a corrupt or truncated .eml, a file that is not an email at all (e.g. a renamed .txt), or input that makes mailparser.parse_from_bytes raise. Note _read_bytes TypeError is also caught here since it inherits Exception.

Common situations: Bulk-ingesting mixed mail archives where some files are broken; files with legacy non-UTF8 encodings; disk/permission errors on the email path.

Related errors


AI-assisted analysis of docling-project/docling@61d76f1ff3 (2026-08-14). Data as JSON: /api/errors/05ef813b8f0c96ec. Report an issue: GitHub.