# Email Parsing

> 将原始邮件文件解析为规范化的结构化对象，包含邮件头、正文和附件，可直接用于分类或抽取流水线。

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

- 标识: `ai.email.parse`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

将原始邮件文件解析为规范化的结构化对象，包含邮件头、正文和附件，可直接用于分类或抽取流水线。

双格式分发：Microsoft Outlook MSG（CFBF / OLE 复合文件容器）使用 `extract-msg`，标准 RFC 822 / MIME EML 邮件使用 `mail-parser`。格式根据魔数自动检测，也可手动指定。

**功能特性：**
- **邮件头规范化：** From、To、CC、BCC、Reply-To、Subject、Message-Id、In-Reply-To 和 Received-Date 解码为标准形式（日期为 ISO-8601，地址列表为数组）。
- **正文处理：** 直接返回纯文本正文；若只有 HTML 部分，则转换为文本，并保留段落和列表的分隔。
- **附件：** 每个附件以 `{ name, content_type, size, content_base64 }` 形式输出，可通过 `flow.split` 交给各类抽取器（PDF、DOCX、OCR 等）。
- **内联与附加：** 在元数据中区分内联附件（例如通过 Content-Id 引用的嵌入图片）与用户添加的附件。
- **编码恢复：** 透明处理 MIME encoded-word 主题（UTF-8、Latin-1、ISO-2022-JP）以及 quoted-printable / base64 正文。
- **格式异常的输入：** 邮件既无正文也无附件时触发 `empty` 端口；容器本身损坏时触发 `error` 端口并附带跟踪详情。

## 配置

- `format` (string, 可选): 手动指定格式，覆盖自动检测。留空则自动检测。 可选值: `msg`, `eml`.

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `extracted` (默认): Parsed
- `empty`: Empty
- `error`: Error

## 输入契约

- `content_base64` (string, 可选)
- `file_path` (string, 可选)

## 输出契约

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

## 在表达式中

后续节点可通过 `$("Email Parsing").item.json.<路径>` 读取此节点输出中的内容（请把 `Email Parsing` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `extracted` 返回的路径，依据“端口”一节所示的输出。

- `$("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` (编辑器不提示)


## 工作原理

解析单封 Outlook MSG 或 RFC 822 EML 邮件，返回邮件头、纯文本正文以及 base64 格式的附件。

1. 从节点配置读取 `content_base64` 和 `file_path`，缺失时回退到上游载荷；两者都没有时从 `error` 输出。主机上存在的 `file_path` 优先于 `content_base64`。
2. 确定格式：若配置了 `format` 则使用它；否则依据文件名的 `.msg`/`.eml`，再检查首字节的 OLE 签名（MSG）；其余一律按 EML 解析。
3. 提取主题、发件人、`to` 与 `cc` 列表、日期和正文。优先使用纯文本正文；没有时将 HTML 正文转为文本（若转换无结果则保留原始 HTML）。
4. 每个附件转换为 `{ name, content_type, size, content_base64 }`；无名附件命名为 `attachment`。
5. 正文为空且没有附件时从 `empty` 输出，否则从 `extracted` 输出。

## 在工作流中

### 节点

```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"
}
```

## 输出端口 (代码中的行为)

### `extracted`

邮件有正文或至少一个附件。

```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`

邮件既没有正文文本也没有附件。

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

### `error`

未提供输入、文件无法解析或脚本失败。

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

## 代码中的行为

- `content_base64, file_path`: 未在配置 schema 中声明，但会先从节点配置读取，再从上游载荷读取。通常用表达式从上一个节点映射。
- `format`: 仅从节点配置读取（不从载荷读取）。强制指定错误格式会导致解析失败。
- `execution`: 仅读取 `execution.timeout_ms`（缺省回退 120000 毫秒）。`retryOnFail`、`maxTries`、`waitBetweenTries`、`continueOnFail` 和 `alwaysOutputData` 均被忽略。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 节点配置和上游载荷都没有提供文件。请从上一个节点映射 `content_base64`（或 `file_path`）。 |
| `Either content_base64 or file_path is required` | `error` | 当只提供了 `file_path` 而主机上不存在该文件时，由脚本抛出（末尾无句点）。 |
| `<parser exception message>` | `error` | Python 解析器抛出异常（把 MSG 强制按 EML 解析或反之，或文件已损坏）。该消息原样放入 `data.error`，脚本的 stderr 放入 `data.stderr`。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超出了节点超时。请调大 `execution.timeout_ms` 或发送更小的文件。 |
| `Python stdout exceeded MAX_STDOUT_BYTES (52428800 bytes)` | `error` | 结果（文本或 base64 文件）超过 50 MB 上限。请在上游拆分输入。 |
| `Python runtime not available (ENOENT)` | `error` | 主机上没有 Python 解释器。若依赖安装失败，消息为 `PythonRunner failed: <message>`。两者都是主机问题，而非工作流问题。 |

## 说明与限制

- 在子进程中运行 Python 脚本。某台 worker 主机上的首次运行会创建虚拟环境并安装脚本锁定的依赖（可能耗时数分钟，且不计入节点超时）；之后的运行会复用该环境。
- `file_path` 必须指向运行该节点的编排器主机本地磁盘上的文件；它不是 URL，也不会从存储中下载。
- 脚本会在 `execution.timeout_ms` 到期后被终止；未设置该键时代码使用 120000 毫秒，而不是 schema 默认的 300000。
- 脚本返回的 JSON 上限为 50 MB（52428800 字节，可在主机上配置）。文件以 base64 传输，较大的输入或输出可能触及该上限。
- 对于 MSG，`to` 和 `cc` 按 `;` 拆分，`from` 为发件人字符串，附件 `content_type` 依据文件名推断。对于 EML，地址格式为 `Name <email>`，`content_type` 取自邮件本身。
- `received_at` 是解析器给出的邮件日期文本，未规范化为 ISO 8601。
- 可配合对 `attachments` 使用 `flow.split`，在下游逐个处理附件。


## 契约（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
  }
]
```
