# 示例：POP3 接收邮件授权（直接录入凭证）

## 1) 创建平台

```bash
curl -X POST http://127.0.0.1:8000/v1/platforms \
  -H 'content-type: application/json' \
  -d '{
    "id":"plat_pop3_demo",
    "orgId":"org_demo",
    "nameId":"pop3_demo",
    "name":"POP3 邮件服务 (Demo)",
    "code":"pop3_demo"
  }'
```

## 2) 创建授权方式（POP3 类型，直接字段）

```bash
curl -X POST http://127.0.0.1:8000/v1/auth-methods \
  -H 'content-type: application/json' \
  -d '{
    "id": "am_pop3_direct",
    "platformId": "plat_pop3_demo",
    "name": "pop3_direct_receive",
    "type": "POP3",
    "description": "直接录入 POP3 服务器连接参数，用于邮件拉取",
    "loginFieldsSchema": {
      "type": "object",
      "required": ["pop3_host", "username", "password"],
      "properties": {
        "pop3_host": {"type": "string"},
        "pop3_port": {"type": "integer", "default": 995},
        "username": {"type": "string"},
        "password": {"type": "string", "format": "password"}
      }
    },
    "responseMapping": {
      "source": "direct",
      "fields": {
        "pop3_host": "pop3_host",
        "pop3_port": "pop3_port",
        "username": "username",
        "password": "password"
      }
    },
    "authFieldPlacements": {
      "metadata": {
        "pop3": {
          "hostField": "pop3_host",
          "portField": "pop3_port",
          "userField": "username",
          "passField": "password",
          "useSSL": true
        }
      }
    }
  }'
```

## 3) 创建 Secret（录入 POP3 凭证）

```bash
curl -X POST http://127.0.0.1:8000/v1/auth-methods/am_pop3_direct/secret \
  -H 'content-type: application/json' \
  -d '{
    "id": "sec_pop3_demo",
    "name": "pop3_account",
    "tags": ["mail","inbound"],
    "data": {
      "pop3_host": "pop3.example.com",
      "pop3_port": 995,
      "username": "user@example.com",
      "password": "<POP3_PASSWORD>"
    },
    "autoLoginEnabled": false
  }'
```

## 4) 客户端使用（Python poplib）

```python
import poplib, ssl, requests
BASE = "http://127.0.0.1:8000"
SECRET_ID = "sec_pop3_demo"
resp = requests.get(f"{BASE}/v1/secrets/{SECRET_ID}")
resp.raise_for_status()
secret = resp.json()
meta = (secret.get("usageMapping", {}).get("metadata", {}) or {}).get("pop3", {})

host = secret['data'].get(meta.get('hostField', 'pop3_host'))
port = secret['data'].get(meta.get('portField', 'pop3_port'), 995)
user = secret['data'].get(meta.get('userField', 'username'))
password = secret['data'].get(meta.get('passField', 'password'))

pop_conn = poplib.POP3_SSL(host, port)  # useSSL=true -> POP3_SSL
pop_conn.user(user)
pop_conn.pass_(password)
num_messages = len(pop_conn.list()[1])
print('messages:', num_messages)
if num_messages:
    resp_lines = pop_conn.retr(1)[1]
    print('\n'.join(line.decode('utf-8', errors='ignore') for line in resp_lines[:20]))
pop_conn.quit()
```

## 5) 客户端使用（Node.js，利用 `node-poplib` 或自定义）

示例使用假设包名（实际可选择合适的 POP3 库，如 `emailjs-imap-client` 处理 IMAP；POP3 可选社区库）。以下为概念示例：

```bash
npm install node-fetch@3 poplib
```

```js
import fetch from 'node-fetch';
import { POP3Client } from 'poplib';

async function main() {
  const res = await fetch('http://127.0.0.1:8000/v1/secrets/sec_pop3_demo');
  const secret = await res.json();
  const meta = (secret.usageMapping?.metadata || {}).pop3 || {};
  const data = secret.data || {};
  const host = data[meta.hostField || 'pop3_host'];
  const port = data[meta.portField || 'pop3_port'] || 995;
  const user = data[meta.userField || 'username'];
  const pass = data[meta.passField || 'password'];

  const client = new POP3Client(port, host, { tlserrs: false, enabletls: true, debug: false });
  client.on('error', err => console.error('POP3 error', err));
  client.on('connect', () => client.login(user, pass));
  client.on('login', status => {
    if (!status) return console.error('login failed');
    client.list();
  });
  client.on('list', (status, msgcount) => {
    if (status) {
      console.log('messages:', msgcount);
      if (msgcount > 0) client.retr(1);
      else client.quit();
    }
  });
  client.on('retr', (status, msgnumber, data) => {
    if (status) console.log('msg snippet:\n', data.split('\n').slice(0, 20).join('\n'));
    client.quit();
  });
}

main().catch(console.error);
```

---

## 6) 要点

- POP3 同样不走 HTTP 登录；`responseMapping.source=direct` 将表单字段写入 `Secret.data`。
- 所有连接参数置于 `metadata.pop3`，客户端据此选择 SSL/端口等策略。
- 若平台需要 STARTTLS 或明文再升级，可将 `useSSL` 改为其他枚举（如 `security: starttls`）。
