# Email Parsing

> Convierte archivos de correo en bruto en un objeto estructurado y normalizado con encabezados, cuerpo y adjuntos, listo para pipelines de clasificación o extracción.

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

- Slug: `ai.email.parse`
- Familia: IA
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Convierte archivos de correo en bruto en un objeto estructurado y normalizado con encabezados, cuerpo y adjuntos, listo para pipelines de clasificación o extracción.

Despachador de doble formato: `extract-msg` para Microsoft Outlook MSG (contenedor de archivo compuesto CFBF / OLE) y `mail-parser` para mensajes EML estándar RFC 822 / MIME. El formato se detecta automáticamente por sus magic bytes, con la opción de forzarlo.

**Características:**
- **Normalización de encabezados:** From, To, CC, BCC, Reply-To, Subject, Message-Id, In-Reply-To y Received-Date se decodifican a una forma canónica (ISO-8601 para las fechas, arreglos para las listas de direcciones).
- **Manejo del cuerpo:** Devuelve directamente el cuerpo en texto plano; cuando solo hay una parte HTML, la convierte a texto conservando los saltos de párrafo y de lista.
- **Adjuntos:** Cada adjunto se emite como `{ name, content_type, size, content_base64 }` para que pueda pasar por `flow.split` hacia los extractores (PDF, DOCX, OCR, etc.).
- **En línea frente a adjuntos:** Distingue en los metadatos los adjuntos en línea (p. ej., imágenes incrustadas referenciadas por Content-Id) de los adjuntos del usuario.
- **Recuperación de codificación:** Maneja de forma transparente asuntos codificados como MIME encoded-word (UTF-8, Latin-1, ISO-2022-JP) y cuerpos en quoted-printable o base64.
- **Entrada mal formada:** Emite el puerto `empty` cuando el correo no tiene cuerpo ni adjuntos, y `error` con el detalle de la traza cuando el propio contenedor está dañado.

## Configuración

- `format` (string, opcional): Fuerza el formato en lugar de detectarlo. Déjalo vacío para la detección automática. Valores permitidos: `msg`, `eml`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `extracted` (por defecto): Parsed
- `empty`: Empty
- `error`: Error

## Contrato de entrada

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

## Contrato de salida

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

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Email Parsing").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Email Parsing`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `extracted`, según la salida que muestra Puertos.

- `$("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` (El editor no la sugiere)


## Cómo funciona

Analiza un mensaje MSG de Outlook o EML (RFC 822) y devuelve encabezados, cuerpo en texto plano y adjuntos como archivos en base64.

1. Lee `content_base64` y `file_path` de la configuración del nodo y, si faltan, del payload anterior; sale por `error` si faltan ambos. Un `file_path` que existe en el host gana sobre `content_base64`.
2. Elige el formato: `format` de la configuración si está definido; si no, `.msg`/`.eml` por el nombre del archivo y luego la firma OLE de los primeros bytes (MSG); todo lo demás se analiza como EML.
3. Extrae asunto, remitente, listas `to` y `cc`, fecha y cuerpo. Se prefiere el cuerpo en texto plano; si falta, el cuerpo HTML se convierte a texto (o se deja como HTML crudo si la conversión no produce nada).
4. Cada adjunto se convierte en `{ name, content_type, size, content_base64 }`; los adjuntos sin nombre se llaman `attachment`.
5. Sale por `empty` si el cuerpo está vacío y no hay adjuntos; si no, por `extracted`.

## En un workflow

### Nodo

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

## Puertos de salida (comportamiento en el código)

### `extracted`

El mensaje tiene cuerpo o al menos un adjunto.

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

El mensaje no tiene texto en el cuerpo ni adjuntos.

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

### `error`

No se recibió entrada, el archivo no se pudo analizar o el script falló.

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

## Comportamiento en el código

- `content_base64, file_path`: No están declaradas en el esquema de configuración, pero se leen primero de la configuración del nodo y luego del payload anterior. Lo habitual es mapearlas desde el nodo previo con expresiones.
- `format`: Se lee solo de la configuración del nodo (no del payload). Forzar un formato equivocado hace fallar el parser.
- `execution`: Solo se lee `execution.timeout_ms` (valor de respaldo 120000 ms). `retryOnFail`, `maxTries`, `waitBetweenTries`, `continueOnFail` y `alwaysOutputData` se ignoran.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | Ni la configuración del nodo ni el payload anterior traen el archivo. Mapea `content_base64` (o `file_path`) desde el nodo previo. |
| `Either content_base64 or file_path is required` | `error` | Lo lanza el script (sin punto final) cuando solo se pasó `file_path` y el archivo no existe en el host. |
| `<parser exception message>` | `error` | El parser de Python lanzó una excepción (un MSG forzado como EML o al revés, o un archivo dañado). El mensaje llega tal cual en `data.error`, con el stderr del script en `data.stderr`. |
| `Python timed out after <timeout_ms>ms` | `error` | El script superó el timeout del nodo. Sube `execution.timeout_ms` o envía un archivo más pequeño. |
| `Python stdout exceeded MAX_STDOUT_BYTES (52428800 bytes)` | `error` | El resultado (texto o archivos en base64) supera el tope de 50 MB. Divide la entrada antes de este nodo. |
| `Python runtime not available (ENOENT)` | `error` | El host no tiene intérprete de Python. Si falla la instalación de dependencias, el mensaje es `PythonRunner failed: <message>`. Ambos son problemas del host, no del flujo. |

## Notas y límites

- Ejecuta un script de Python en un proceso hijo. La primera ejecución en un host crea un entorno virtual e instala las dependencias fijadas del script (puede tardar minutos y no cuenta para el timeout del nodo); las siguientes lo reutilizan.
- `file_path` debe apuntar a un archivo en el disco local del host del orquestador que ejecuta el nodo; no es una URL y no se descarga de ningún almacenamiento.
- El script se termina al cumplirse `execution.timeout_ms`; si esa clave no está definida, el código usa 120000 ms, no el valor por defecto del esquema (300000).
- La respuesta JSON del script tiene un tope de 50 MB (52428800 bytes, configurable en el host). Como los archivos viajan en base64, entradas o salidas grandes pueden alcanzar ese tope.
- En MSG, `to` y `cc` se separan por `;`, `from` es el texto del remitente y el `content_type` de los adjuntos se deduce del nombre. En EML, las direcciones se formatean como `Nombre <correo>` y el `content_type` viene del mensaje.
- `received_at` es la fecha del mensaje como texto, en el formato que entrega el parser; no se normaliza a ISO 8601.
- Combínalo con `flow.split` sobre `attachments` para procesar cada adjunto aguas abajo.


## Contratos (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
  }
]
```
