# Outlook - Attachments

> Descarga y gestiona los adjuntos de correos de Microsoft Outlook mediante Microsoft Graph API.

Source: https://docs.sommatic.ai/es/nodes/connectors.microsoft.outlook.attachments/

- Slug: `connectors.microsoft.outlook.attachments`
- Familia: Conectores
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Descarga y gestiona los adjuntos de correos de Microsoft Outlook mediante Microsoft Graph API.

Manejador de adjuntos dedicado para entornos corporativos con procesamiento de correo de alto volumen. Admite filtrado por tipo y tamaño, paginación para correos con muchos adjuntos y escritura en disco por streaming para archivos grandes.

**Operaciones:**
- **List:** Obtiene los metadatos de todos los adjuntos (nombre, tipo, tamaño) sin descargar el contenido.
- **Download:** Descarga el contenido del adjunto en base64 o lo escribe directamente en archivos temporales.
- **Download All:** Descarga todos los adjuntos de un mensaje con filtrado opcional.

## Configuración

- `connection_id` (string, obligatorio): Credencial de acceso a Microsoft Graph API. Acepta credenciales de tipo `oauth2` (token de acceso + token de actualización), `service-account` (tenant id + client id + client secret) u `object` (configuración avanzada de Graph).
- `mailbox_mode` (string, opcional): Por defecto: `token_owner`. Valores permitidos: `token_owner`, `other`.
- `mailbox_email` (string, opcional, acepta expresiones): Se muestra cuando: mailbox_mode = `other`.
- `message_source` (string, opcional): Incoming: usa el ID del correo del nodo anterior. Custom: indica un ID de mensaje manualmente. Por defecto: `incoming`. Valores permitidos: `incoming`, `custom`.
- `custom_message_id` (string, opcional, acepta expresiones): Se muestra cuando: message_source = `custom`.
- `filter_content_type` (string, opcional, acepta expresiones): Filtro opcional por tipo MIME (p. ej., "application/pdf", "image/"). Admite coincidencia por prefijo.
- `filter_min_size` (number, opcional): Tamaño mínimo del adjunto en bytes. Útil para excluir imágenes incrustadas.
- `filter_max_size` (number, opcional): Tamaño máximo del adjunto en bytes.
- `output_mode` (string, opcional): Content: devuelve base64 en el payload. File: escribe en /tmp/ y devuelve las rutas de los archivos (recomendado para adjuntos grandes). Por defecto: `content`. Valores permitidos: `content`, `file`.

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

- `success` (por defecto): Attachments Found
- `no_attachments`: No Attachments
- `error`: Error

## Contrato de entrada

- `id` (string, opcional): ID del mensaje que llega del trigger o del nodo anterior.

## Contrato de salida

- `attachments` (array, opcional): Lista de adjuntos con metadatos y contenido o ruta.
- `count` (number, opcional): Número de adjuntos encontrados.

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("Outlook - Attachments").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `Outlook - Attachments`). **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 `success`, según la salida que muestra Puertos.

- `$("Outlook - Attachments").item.json.attachments` (array) = `[…] (1)`: Lista de adjuntos con metadatos y contenido o ruta.
- `$("Outlook - Attachments").item.json.count` (number) = `1`: Número de adjuntos encontrados.


## Cómo funciona

Descarga los adjuntos de un mensaje de Outlook mediante Microsoft Graph, los filtra por tipo MIME y tamaño, y los devuelve como contenido base64 o como archivos en el orquestador.

1. Resuelve la configuración del nodo y exige `connection_id`. Obtiene un token de Graph: si el secreto de la credencial tiene `client_id`, `client_secret` y `tenant_id`, solicita un token de aplicación (client credentials); si no, usa tal cual el `token` o `access_token` del secreto.
2. Apunta a `/users/<mailbox_email>` cuando `mailbox_mode` es `other`; si no, a `/me`.
3. Toma el id del mensaje de `custom_message_id` cuando `message_source` es `custom`; si no, del `id` del ítem de entrada.
4. Lista todos los adjuntos del mensaje, siguiendo las páginas de `@odata.nextLink`.
5. Conserva los adjuntos cuyo `contentType` empieza por `filter_content_type` y cuyo `size` está entre `filter_min_size` y `filter_max_size`.
6. Devuelve `no_attachments` si no queda ninguno. En otro caso devuelve `success` con `content_bytes` (base64) por adjunto o, en modo `file`, escribe cada uno en un directorio temporal nuevo y devuelve su `file_path`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-get-pdfs",
  "label": "Get PDF attachments",
  "operator_slug": "connectors.microsoft.outlook.attachments",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "mailbox_mode": "other",
    "mailbox_email": "support@example.com",
    "message_source": "incoming",
    "filter_content_type": "application/pdf",
    "filter_min_size": 1024,
    "output_mode": "content"
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "attachments": [
      {
        "id": "AAMkAGI2THVSAAA=",
        "name": "invoice-2026-0418.pdf",
        "content_type": "application/pdf",
        "size": 48213,
        "content_bytes": "JVBERi0xLjcKJc...",
        "is_inline": false
      }
    ],
    "count": 1
  },
  "port": "success"
}
```

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

### `success`

Al menos un adjunto pasó los filtros. En modo `file`, cada elemento trae `file_path` en lugar de `content_bytes`.

```json
{
  "attachments": [
    {
      "id": "AAMkAGI2THVSAAA=",
      "name": "invoice-2026-0418.pdf",
      "content_type": "application/pdf",
      "size": 48213,
      "content_bytes": "JVBERi0xLjcKJc...",
      "is_inline": false
    }
  ],
  "count": 1
}
```

### `no_attachments`

El mensaje no tiene adjuntos o ninguno pasó los filtros.

```json
{
  "attachments": [],
  "count": 0
}
```

### `error`

Falló una validación (la salida es el sobre `{ ok, errors, port }`) o falló una llamada a Graph (la salida es `{ error, response }` con el cuerpo de error de Graph).

```json
{
  "ok": false,
  "errors": [
    "Failed to resolve Microsoft 365 access token"
  ],
  "port": "error"
}
```

## Comportamiento en el código

- `mailbox_mode`: Los tokens de aplicación (client credentials) no tienen `/me`; con ellos usa `other` y `mailbox_email`.
- `filter_content_type`: Coincidencia por prefijo sobre `contentType`, sensible a mayúsculas (por ejemplo `image/` o `application/pdf`).
- `output_mode`: `file` escribe en el directorio temporal del orquestador usando el nombre del adjunto; dos adjuntos con el mismo nombre se sobrescriben, y el nodo no limpia los archivos.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `Microsoft 365 credential is required` | `error` | `connection_id` está vacío. |
| `Failed to resolve Microsoft 365 access token` | `error` | No se pudo resolver la credencial, falló la solicitud del token o el secreto no tiene ni client credentials ni token. La causa de fondo no se informa. |
| `Message ID is required. Ensure the previous node outputs an email with an ID, or select "Custom" and provide a Message ID.` | `error` | El ítem de entrada no tiene `id` y no hay id personalizado. |
| `Request failed with status code <status>` | `error` | Graph rechazó la llamada: 404 si el id del mensaje o el buzón no existen, 401/403 si el token venció o falta el permiso `Mail.Read`. Revisa `response` para ver el error de Graph. |

## Notas y límites

- Un token de acceso OAuth guardado en la credencial se usa tal cual y nunca se renueva; cuando vence, Graph devuelve 401.
- Los adjuntos de tipo elemento o referencia no traen `contentBytes`: `content_bytes` es `null` y, en modo `file`, no se escribe archivo aunque se devuelva `file_path`.
- El modo `content` pone cada adjunto en el estado del workflow como base64; prefiere `file` para archivos grandes. El nodo no reintenta.


## Contratos (JSON Schema)

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

```json
{
  "slug": "connectors.microsoft.outlook.attachments",
  "name": "Outlook - Attachments",
  "category": "integrations",
  "version": "1.0.0",
  "description": "Download and manage email attachments from Microsoft Outlook via Microsoft Graph API.\n\n  Dedicated attachment handler for corporate environments with high-volume email processing. Supports filtering by type, size, pagination for emails with many attachments, and streaming to disk for large files.\n\n  **Operations:**\n  - **List:** Get metadata of all attachments (name, type, size) without downloading content.\n  - **Download:** Download attachment content as base64 or write directly to temporary files.\n  - **Download All:** Download all attachments from a message with optional filtering.",
  "capabilities": [
    "email",
    "attachments",
    "microsoft",
    "outlook",
    "office365"
  ],
  "group": [
    {
      "key": "microsoft",
      "name": "Microsoft",
      "icon_url": "/icons/integrations/microsoft/microsoft.svg"
    },
    {
      "key": "microsoft365",
      "name": "Microsoft 365",
      "icon_url": "/icons/integrations/microsoft/microsoft365.svg"
    }
  ],
  "icon_url": "/icons/integrations/microsoft/outlook.svg",
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "Microsoft 365 Credential",
        "description": "Credential for Microsoft Graph API access. Accepts credentials of type `oauth2` (access + refresh token), `service-account` (tenant id + client id + client secret), or `object` (advanced Graph config).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "oauth2",
            "service-account",
            "object"
          ],
          "types": [
            "outlook",
            "microsoft365",
            "oauth2"
          ]
        }
      },
      "mailbox_mode": {
        "type": "string",
        "title": "Mailbox",
        "enum": [
          "token_owner",
          "other"
        ],
        "default": "token_owner"
      },
      "mailbox_email": {
        "type": "string",
        "title": "Mailbox Email",
        "format": "expression",
        "displayOptions": {
          "show": {
            "mailbox_mode": [
              "other"
            ]
          }
        }
      },
      "message_source": {
        "type": "string",
        "title": "Message Source",
        "enum": [
          "incoming",
          "custom"
        ],
        "default": "incoming",
        "description": "Incoming: uses the email ID from the previous node. Custom: specify a message ID manually."
      },
      "custom_message_id": {
        "type": "string",
        "title": "Message ID",
        "format": "expression",
        "displayOptions": {
          "show": {
            "message_source": [
              "custom"
            ]
          }
        }
      },
      "filter_content_type": {
        "type": "string",
        "title": "Filter by Type",
        "description": "Optional MIME type filter (e.g., \"application/pdf\", \"image/\"). Supports prefix matching.",
        "format": "expression"
      },
      "filter_min_size": {
        "type": "number",
        "title": "Min Size (bytes)",
        "description": "Minimum attachment size in bytes. Useful for filtering out inline images."
      },
      "filter_max_size": {
        "type": "number",
        "title": "Max Size (bytes)",
        "description": "Maximum attachment size in bytes."
      },
      "output_mode": {
        "type": "string",
        "title": "Output Mode",
        "enum": [
          "content",
          "file"
        ],
        "default": "content",
        "description": "Content: returns base64 in payload. File: writes to /tmp/ and returns file paths (recommended for large attachments)."
      },
      "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
          }
        }
      }
    },
    "required": [
      "connection_id"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "id": {
        "type": "string",
        "description": "Message ID from the trigger or previous node."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "attachments": {
        "type": "array",
        "description": "List of attachments with metadata and content/path."
      },
      "count": {
        "type": "number",
        "description": "Number of attachments found."
      }
    }
  },
  "ports": [
    {
      "port_id": "success",
      "label": "Attachments Found",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "no_attachments",
      "label": "No Attachments",
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "email",
    "attachments",
    "microsoft",
    "outlook",
    "download"
  ],
  "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": {
    "connection_id": {
      "type": "string",
      "title": "Microsoft 365 Credential",
      "description": "Credential for Microsoft Graph API access. Accepts credentials of type `oauth2` (access + refresh token), `service-account` (tenant id + client id + client secret), or `object` (advanced Graph config).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "oauth2",
          "service-account",
          "object"
        ],
        "types": [
          "outlook",
          "microsoft365",
          "oauth2"
        ]
      }
    },
    "mailbox_mode": {
      "type": "string",
      "title": "Mailbox",
      "enum": [
        "token_owner",
        "other"
      ],
      "default": "token_owner"
    },
    "mailbox_email": {
      "type": "string",
      "title": "Mailbox Email",
      "format": "expression",
      "displayOptions": {
        "show": {
          "mailbox_mode": [
            "other"
          ]
        }
      }
    },
    "message_source": {
      "type": "string",
      "title": "Message Source",
      "enum": [
        "incoming",
        "custom"
      ],
      "default": "incoming",
      "description": "Incoming: uses the email ID from the previous node. Custom: specify a message ID manually."
    },
    "custom_message_id": {
      "type": "string",
      "title": "Message ID",
      "format": "expression",
      "displayOptions": {
        "show": {
          "message_source": [
            "custom"
          ]
        }
      }
    },
    "filter_content_type": {
      "type": "string",
      "title": "Filter by Type",
      "description": "Optional MIME type filter (e.g., \"application/pdf\", \"image/\"). Supports prefix matching.",
      "format": "expression"
    },
    "filter_min_size": {
      "type": "number",
      "title": "Min Size (bytes)",
      "description": "Minimum attachment size in bytes. Useful for filtering out inline images."
    },
    "filter_max_size": {
      "type": "number",
      "title": "Max Size (bytes)",
      "description": "Maximum attachment size in bytes."
    },
    "output_mode": {
      "type": "string",
      "title": "Output Mode",
      "enum": [
        "content",
        "file"
      ],
      "default": "content",
      "description": "Content: returns base64 in payload. File: writes to /tmp/ and returns file paths (recommended for large attachments)."
    },
    "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
        }
      }
    }
  },
  "required": [
    "connection_id"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "id": {
      "type": "string",
      "description": "Message ID from the trigger or previous node."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "attachments": {
      "type": "array",
      "description": "List of attachments with metadata and content/path."
    },
    "count": {
      "type": "number",
      "description": "Number of attachments found."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "success",
    "label": "Attachments Found",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "no_attachments",
    "label": "No Attachments",
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "supports_condition": false
  }
]
```
