# Read Email (IMAP)

> 从 IMAP 服务器读取邮件。

Source: https://docs.sommatic.ai/zh/nodes/io.imap/

- 标识: `io.imap`
- 类别: 输入与输出
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

从 IMAP 服务器读取邮件。

## 配置

- `connection_id` (string, 必填): IMAP 邮件服务器的凭据。接受 `basic-auth`（用户名 + 密码 + 主机 + 端口）类型的凭据。
- `box` (string, 可选): 默认值: `INBOX`.
- `searchCriteria` (array, 可选): 搜索条件，例如 UNSEEN、ALL 或 ['SINCE', date] 默认值: `["UNSEEN"]`.
- `markSeen` (boolean, 可选): 默认值: `true`.

## 输出端口

- `out` (默认): 找到的邮件列表
- `empty`: 未找到符合条件的邮件
- `error`: 连接或获取错误

## 输入契约

- `connection_id` (string, 必填)
- `box` (string, 可选)
- `searchCriteria` (array, 可选)
- `markSeen` (boolean, 可选)

## 输出契约

- `emails` (array, 可选): 找到的邮件列表

## 在表达式中

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

- `$("Read Email (IMAP)").item.json.emails` (array) = `[…] (1)`: 找到的邮件列表


## 工作原理

连接 IMAP 邮箱，按 IMAP 条件搜索一个文件夹，返回匹配邮件的主题、发件人、日期、原始文本正文和属性；无匹配时从 `empty` 输出。

1. 解析配置。`connection_id`、`box`（默认 `INBOX`）、`searchCriteria`（默认 `["UNSEEN"]`）和 `markSeen`（默认 true）缺失时回退到输入 payload 中的同名键；空的 `box` 或空条件数组视为未设置。
2. 解析凭据：`host`、`port`（默认 993）和 `tls`（默认 true）取自凭据配置；`username`（或 `user`）和 `password`（或 `pass`）取自密钥。认证最多等待 10 秒。
3. 打开 `box`，执行搜索，并获取每封匹配邮件的 `HEADER` 和 `TEXT` 部分。启用 `markSeen` 时，已获取的邮件会被标记为已读。
4. 将每封邮件映射为 `{ subject, from, date, body, attributes }`，然后关闭连接。
5. 至少有一封邮件时以 `{ emails }` 从 `out` 输出；没有邮件时以 `{}` 从 `empty` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-read-invoices",
  "label": "Read invoice mailbox",
  "operator_slug": "io.imap",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "box": "INBOX",
    "searchCriteria": [
      "UNSEEN"
    ],
    "markSeen": true
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "emails": [
      {
        "subject": "Invoice INV-2026-0042",
        "from": "Billing <billing@example.com>",
        "date": "Wed, 25 Nov 2026 14:12:09 +0000",
        "body": "Hello,\r\nPlease find the invoice attached.\r\n",
        "attributes": {
          "uid": 1842,
          "flags": [
            "\\Seen"
          ],
          "date": "2026-11-25T14:12:09.000Z"
        }
      }
    ]
  },
  "port": "out"
}
```

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

### `out`

搜索至少匹配一封邮件。`subject`、`from` 和 `date` 为各邮件头的第一个值；`body` 为原始 `TEXT` 部分（多部分邮件为 MIME 源码）；`attributes` 包含 IMAP 的 `uid`、`flags` 和 `date`。

```json
{
  "emails": [
    {
      "subject": "Invoice INV-2026-0042",
      "from": "Billing <billing@example.com>",
      "date": "Wed, 25 Nov 2026 14:12:09 +0000",
      "body": "Hello,\r\nPlease find the invoice attached.\r\n",
      "attributes": {
        "uid": 1842,
        "flags": [
          "\\Seen"
        ],
        "date": "2026-11-25T14:12:09.000Z"
      }
    }
  ]
}
```

### `empty`

搜索未匹配到任何邮件。

```json
{}
```

### `error`

缺少 `connection_id`，或凭据、连接、登录、文件夹、搜索失败。数据为 `{ error, details }`，其中 `details` 包含错误的 `code`、`stack` 及其原始序列化内容。

```json
{
  "error": "Invalid credentials (Failure)",
  "details": {
    "code": null,
    "stack": "<stack>",
    "raw": "<serialized error>"
  }
}
```

## 代码中的行为

- `searchCriteria`: 以数组形式给出的 IMAP 搜索条件，例如 `["UNSEEN"]`、`["ALL"]` 或 `["UNSEEN", ["SINCE", "2026-11-01"]]`。空数组会回退到 payload，再回退到 `["UNSEEN"]`。
- `markSeen`: 只有显式设为 `false` 才会保持邮件未读。在默认 `UNSEEN` 条件下，正是该设置使下一次运行不会返回相同的邮件。
- `connection_id`: 接受 `basic-auth` 凭据。包含 `:` 的值或 JSON 对象会被视为本地测试用的原始 `host:port`，用户名和密码从输入 payload 读取。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `connection_id is required (check config or config.payload)` | `error` | 配置和输入 payload 中都没有凭据。请选择一个 IMAP 凭据。 |
| `<IMAP server error>` | `error` | 用户名或密码错误、`box` 指定的文件夹不存在，或搜索条件无效。若邮件服务商要求使用应用专用密码，请将其保存在凭据中。 |
| `Failed to resolve connection <connection_id>: <detail>` | `error` | 凭据不存在或此工作流无权使用。 |

## 说明与限制

- 一次运行会获取所有匹配邮件，没有数量限制或分页；在大型邮箱中请收窄 `searchCriteria`。
- 不会提取附件，附件保留在原始 MIME `body` 中。
- `markSeen: true` 时不具备幂等性：每次运行都会改变邮箱状态。


## 契约（JSON Schema）

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

```json
{
  "slug": "io.imap",
  "name": "Read Email (IMAP)",
  "category": "io",
  "version": "1.0.0",
  "description": "Read emails from IMAP server.",
  "capabilities": [
    "email",
    "imap",
    "communication"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "IMAP Credential",
        "description": "Credential for the IMAP mail server. Accepts credentials of type `basic-auth` (username + password + host + port).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "basic-auth"
          ],
          "types": [
            "imap"
          ]
        }
      },
      "box": {
        "type": "string",
        "default": "INBOX"
      },
      "searchCriteria": {
        "type": "array",
        "default": [
          "UNSEEN"
        ],
        "description": "Criteria like UNSEEN, ALL, or ['SINCE', date]"
      },
      "markSeen": {
        "type": "boolean",
        "default": true
      }
    },
    "required": [
      "connection_id"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "box": {
        "type": "string"
      },
      "searchCriteria": {
        "type": "array"
      },
      "markSeen": {
        "type": "boolean"
      }
    },
    "required": [
      "connection_id"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "emails": {
        "type": "array",
        "description": "List of found emails"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Emails",
      "description": "List of found emails",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "No Emails",
      "description": "No emails found matching criteria",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Connection or fetch error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io"
  ],
  "tags": [
    "email",
    "communication"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "IMAP Credential",
      "description": "Credential for the IMAP mail server. Accepts credentials of type `basic-auth` (username + password + host + port).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "basic-auth"
        ],
        "types": [
          "imap"
        ]
      }
    },
    "box": {
      "type": "string",
      "default": "INBOX"
    },
    "searchCriteria": {
      "type": "array",
      "default": [
        "UNSEEN"
      ],
      "description": "Criteria like UNSEEN, ALL, or ['SINCE', date]"
    },
    "markSeen": {
      "type": "boolean",
      "default": true
    }
  },
  "required": [
    "connection_id"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "box": {
      "type": "string"
    },
    "searchCriteria": {
      "type": "array"
    },
    "markSeen": {
      "type": "boolean"
    }
  },
  "required": [
    "connection_id"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "emails": {
      "type": "array",
      "description": "List of found emails"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Emails",
    "description": "List of found emails",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "No Emails",
    "description": "No emails found matching criteria",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Connection or fetch error",
    "is_default": false,
    "supports_condition": false
  }
]
```
