# Email Parsing

> Parses raw email files into a normalized structured object with headers, body, and attachments, ready for classification or extraction pipelines.

Source: https://docs.sommatic.ai/en/nodes/ai.email.parse/

- Slug: `ai.email.parse`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Parses raw email files into a normalized structured object with headers, body, and attachments, ready for classification or extraction pipelines.

Dual-format dispatcher: `extract-msg` for Microsoft Outlook MSG (CFBF / OLE compound-file container) and `mail-parser` for standard RFC 822 / MIME EML messages. Format detection is automatic based on magic bytes, with an optional override.

**Features:**
- **Header normalization:** From, To, CC, BCC, Reply-To, Subject, Message-Id, In-Reply-To, and Received-Date decoded to canonical form (ISO-8601 for dates, arrays for address lists).
- **Body handling:** Returns plain-text body directly; when only an HTML part is present, converts to text while preserving paragraph and list breaks.
- **Attachments:** Each attachment emitted as `{ name, content_type, size, content_base64 }` so it can be piped through `flow.split` to extractors (PDF, DOCX, OCR, etc.).
- **Inline vs attached:** Distinguishes inline attachments (e.g. embedded images referenced by Content-Id) from user attachments in metadata.
- **Encoding recovery:** Handles MIME-encoded-word subjects (UTF-8, Latin-1, ISO-2022-JP) and quoted-printable / base64 bodies transparently.
- **Malformed input:** Emits port `empty` when the email has no body or attachments, and `error` with trace detail when the container itself is corrupt.

## Configuration

- `format` (string, optional): Override format detection. Leave empty to auto-detect. Allowed values: `msg`, `eml`.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `extracted` (default): Parsed
- `empty`: Empty
- `error`: Error

## Input contract

- `content_base64` (string, optional)
- `file_path` (string, optional)

## Output contract

- `format` (string, optional)
- `subject` (string, optional)
- `from` (string, optional)
- `to` (array<string>, optional)
- `cc` (array<string>, optional)
- `received_at` (string, optional)
- `body` (string, optional)
- `attachments` (array<object>, optional)
- `chars` (number, optional)
- `empty` (boolean, optional)
- `method` (string, optional)
- `metadata` (object, optional)

## In expressions

What a later node can read from this node's output with `$("Email Parsing").item.json.<path>` (write your node's label instead of `Email Parsing`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `extracted`, from the output shown in Ports.

- `$("Email Parsing").item.json.format` (string) = `"eml"`
- `$("Email Parsing").item.json.subject` (string) = `"Invoice 2026-10"`
- `$("Email Parsing").item.json.from` (string) = `"Billing <billing@example.com>"`
- `$("Email Parsing").item.json.to` (array) = `[…] (1)`
- `$("Email Parsing").item.json.cc` (array) = `[…] (0)`
- `$("Email Parsing").item.json.received_at` (string) = `"2026-11-20 14:03:11+00:00"`
- `$("Email Parsing").item.json.body` (string) = `"Please find the October invoice attached."`
- `$("Email Parsing").item.json.attachments` (array) = `[…] (1)`
- `$("Email Parsing").item.json.chars` (number) = `41`
- `$("Email Parsing").item.json.empty` (boolean) = `false`
- `$("Email Parsing").item.json.method` (string) = `"email-eml"`
- `$("Email Parsing").item.json.metadata` (object) = `{…}`
- `$("Email Parsing").item.json.metadata.attachments_count` (number) = `1` (Not suggested by the editor)


## How it works

Parses one Outlook MSG or RFC 822 EML message into headers, a plain-text body and its attachments as base64 files.

1. Reads `content_base64` and `file_path` from the node config, falling back to the upstream payload; fails on `error` when both are missing. A `file_path` that exists on the host wins over `content_base64`.
2. Picks the format: `format` from the config if set; otherwise `.msg`/`.eml` from the file name, then the OLE signature of the first bytes (MSG); anything else is parsed as EML.
3. Extracts subject, sender, `to` and `cc` lists, date and body. The plain-text body is preferred; when it is missing, the HTML body is converted to text (or kept as raw HTML if conversion yields nothing).
4. Each attachment becomes `{ name, content_type, size, content_base64 }`; nameless attachments are called `attachment`.
5. Routes to `empty` when the body is empty and there are no attachments, otherwise to `extracted`.

## In a workflow

### Node

```json
{
  "node_id": "node-parse-email",
  "label": "Parse email",
  "operator_slug": "ai.email.parse",
  "operator_version": "1.0.0",
  "config": {
    "content_base64": "{{ $json.content_base64 }}",
    "format": "eml",
    "execution": {
      "timeout_ms": 120000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "format": "eml",
    "subject": "Invoice 2026-10",
    "from": "Billing <billing@example.com>",
    "to": [
      "ap@example.org"
    ],
    "cc": [],
    "received_at": "2026-11-20 14:03:11+00:00",
    "body": "Please find the October invoice attached.",
    "attachments": [
      {
        "name": "invoice-2026-10.pdf",
        "content_type": "application/pdf",
        "size": 48213,
        "content_base64": "JVBERi0xLjcK..."
      }
    ],
    "chars": 41,
    "empty": false,
    "method": "email-eml",
    "metadata": {
      "attachments_count": 1
    }
  },
  "port": "extracted"
}
```

## Output ports (behaviour in the code)

### `extracted`

The message has a body or at least one attachment.

```json
{
  "format": "eml",
  "subject": "Invoice 2026-10",
  "from": "Billing <billing@example.com>",
  "to": [
    "ap@example.org"
  ],
  "cc": [],
  "received_at": "2026-11-20 14:03:11+00:00",
  "body": "Please find the October invoice attached.",
  "attachments": [
    {
      "name": "invoice-2026-10.pdf",
      "content_type": "application/pdf",
      "size": 48213,
      "content_base64": "JVBERi0xLjcK..."
    }
  ],
  "chars": 41,
  "empty": false,
  "method": "email-eml",
  "metadata": {
    "attachments_count": 1
  }
}
```

### `empty`

The message has neither body text nor attachments.

```json
{
  "format": "msg",
  "subject": "",
  "from": "",
  "to": [],
  "cc": [],
  "received_at": "",
  "body": "",
  "attachments": [],
  "chars": 0,
  "empty": true,
  "method": "email-msg",
  "metadata": {
    "attachments_count": 0
  }
}
```

### `error`

No input was given, the file could not be parsed or the script failed.

```json
{
  "error": "Either content_base64 or file_path is required",
  "stderr": ""
}
```

## Behaviour in the code

- `content_base64, file_path`: Not declared in the config schema, but read from the node config first and then from the upstream payload. Usually you map them from the previous node with expressions.
- `format`: Read from the node config only (not from the payload). Forcing the wrong format makes the parser fail.
- `execution`: Only `execution.timeout_ms` is read (fallback 120000 ms). `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail` and `alwaysOutputData` are ignored.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | Neither the node config nor the upstream payload carries the file. Map `content_base64` (or `file_path`) from the previous node. |
| `Either content_base64 or file_path is required` | `error` | Raised by the script (no trailing period) when only `file_path` was given and the file does not exist on the host. |
| `<parser exception message>` | `error` | The Python parser raised an exception (an MSG forced as EML or the reverse, or a damaged file). The message is passed through as `data.error`, with the script's stderr in `data.stderr`. |
| `Python timed out after <timeout_ms>ms` | `error` | The script exceeded the node timeout. Raise `execution.timeout_ms` or send a smaller file. |
| `Python stdout exceeded MAX_STDOUT_BYTES (52428800 bytes)` | `error` | The result (text or base64 files) is larger than the 50 MB cap. Split the input upstream. |
| `Python runtime not available (ENOENT)` | `error` | The host has no Python interpreter. A failed dependency install shows `PythonRunner failed: <message>` instead. Both are host problems, not workflow problems. |

## Notes and limits

- Runs a Python script in a child process. The first run on a worker host creates a virtual environment and installs the script's pinned dependencies (it can take minutes and is not counted in the node timeout); later runs reuse it.
- `file_path` must point to a file on the local disk of the orchestrator host that runs the node; it is not a URL and is not fetched from storage.
- The script is killed after `execution.timeout_ms`; when that key is not set the code uses 120000 ms, not the schema default of 300000.
- The script's JSON answer is capped at 50 MB (52428800 bytes, configurable on the host). Because files travel as base64, large inputs or outputs can hit this cap.
- For MSG, `to` and `cc` are split on `;`, `from` is the sender string and attachment `content_type` is guessed from the name. For EML, addresses are formatted as `Name <email>` and `content_type` comes from the message.
- `received_at` is the message date as text, in the format the parser gives; it is not normalised to ISO 8601.
- Pair it with `flow.split` over `attachments` to process each attachment downstream.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "ai.email.parse",
  "name": "Email Parsing",
  "category": "ai",
  "version": "1.0.0",
  "description": "Parses raw email files into a normalized structured object with headers, body, and attachments, ready for classification or extraction pipelines.\n\n  Dual-format dispatcher: `extract-msg` for Microsoft Outlook MSG (CFBF / OLE compound-file container) and `mail-parser` for standard RFC 822 / MIME EML messages. Format detection is automatic based on magic bytes, with an optional override.\n\n  **Features:**\n  - **Header normalization:** From, To, CC, BCC, Reply-To, Subject, Message-Id, In-Reply-To, and Received-Date decoded to canonical form (ISO-8601 for dates, arrays for address lists).\n  - **Body handling:** Returns plain-text body directly; when only an HTML part is present, converts to text while preserving paragraph and list breaks.\n  - **Attachments:** Each attachment emitted as `{ name, content_type, size, content_base64 }` so it can be piped through `flow.split` to extractors (PDF, DOCX, OCR, etc.).\n  - **Inline vs attached:** Distinguishes inline attachments (e.g. embedded images referenced by Content-Id) from user attachments in metadata.\n  - **Encoding recovery:** Handles MIME-encoded-word subjects (UTF-8, Latin-1, ISO-2022-JP) and quoted-printable / base64 bodies transparently.\n  - **Malformed input:** Emits port `empty` when the email has no body or attachments, and `error` with trace detail when the container itself is corrupt.",
  "capabilities": [
    "email",
    "msg",
    "eml",
    "mime",
    "outlook",
    "parsing"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "format": {
        "type": "string",
        "title": "Format (optional)",
        "enum": [
          "msg",
          "eml"
        ],
        "description": "Override format detection. Leave empty to auto-detect."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content_base64": {
        "type": "string"
      },
      "file_path": {
        "type": "string"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "format": {
        "type": "string"
      },
      "subject": {
        "type": "string"
      },
      "from": {
        "type": "string"
      },
      "to": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "cc": {
        "type": "array",
        "items": {
          "type": "string"
        }
      },
      "received_at": {
        "type": "string"
      },
      "body": {
        "type": "string"
      },
      "attachments": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "name": {
              "type": "string"
            },
            "content_type": {
              "type": "string"
            },
            "size": {
              "type": "number"
            },
            "content_base64": {
              "type": "string"
            }
          }
        }
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Parsed",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "Empty",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "email",
    "msg",
    "eml",
    "parse"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "format": {
      "type": "string",
      "title": "Format (optional)",
      "enum": [
        "msg",
        "eml"
      ],
      "description": "Override format detection. Leave empty to auto-detect."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content_base64": {
      "type": "string"
    },
    "file_path": {
      "type": "string"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "format": {
      "type": "string"
    },
    "subject": {
      "type": "string"
    },
    "from": {
      "type": "string"
    },
    "to": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "cc": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "received_at": {
      "type": "string"
    },
    "body": {
      "type": "string"
    },
    "attachments": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string"
          },
          "content_type": {
            "type": "string"
          },
          "size": {
            "type": "number"
          },
          "content_base64": {
            "type": "string"
          }
        }
      }
    },
    "chars": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Parsed",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "Empty",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
