# 示例：SMTP 发送邮件授权（直接录入凭证）

## 1) 创建平台

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

## 2) 创建授权方式（SMTP 类型，直接使用字段，不需要 loginFlow）

使用默认模板（`auth_schemas.yaml` 中的 `SMTP`），可只指定 `type: SMTP` 与必要描述；如果需要把凭证投放给上层发送器，可在 `authFieldPlacements.metadata` 中声明。示例：

```bash
curl -X POST http://127.0.0.1:8000/v1/auth-methods \
  -H 'content-type: application/json' \
  -d '{
    "id": "am_smtp_direct",
    "platformId": "plat_smtp_demo",
    "name": "smtp_direct_send",
    "type": "SMTP",
    "description": "直接录入 SMTP 服务器连接参数，用于邮件发送",
    "loginFieldsSchema": {
      "type": "object",
      "required": ["smtp_host", "username", "password"],
      "properties": {
        "smtp_host": {"type": "string"},
        "smtp_port": {"type": "integer", "default": 587},
        "username": {"type": "string"},
        "password": {"type": "string", "format": "password"}
      }
    },
    "responseMapping": {
      "source": "direct",
      "fields": {
        "smtp_host": "smtp_host",
        "smtp_port": "smtp_port",
        "username": "username",
        "password": "password"
      }
    },
    "authFieldPlacements": {
      "metadata": {
        "smtp": {
          "hostField": "smtp_host",
          "portField": "smtp_port",
          "userField": "username",
          "passField": "password",
          "useTLS": true
        }
      }
    }
  }'
```

## 3) 创建 Secret（录入真实或占位的 SMTP 凭证）

```bash
curl -X POST http://127.0.0.1:8000/v1/auth-methods/am_smtp_direct/secret \
  -H 'content-type: application/json' \
  -d '{
    "id": "sec_smtp_demo",
    "name": "smtp_account",
    "tags": ["mail","outbound"],
    "data": {
      "smtp_host": "smtp.example.com",
      "smtp_port": 587,
      "username": "user@example.com",
      "password": "<SMTP_PASSWORD>"
    },
    "autoLoginEnabled": false
  }'
```

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

```python
import smtplib, ssl, requests
BASE = "http://127.0.0.1:8000"
SECRET_ID = "sec_smtp_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("smtp", {})
# 如果 usageMapping 不存在，可直接从 secret['data'] 取字段

host = secret['data'].get(meta.get('hostField', 'smtp_host'))
port = secret['data'].get(meta.get('portField', 'smtp_port'), 587)
user = secret['data'].get(meta.get('userField', 'username'))
password = secret['data'].get(meta.get('passField', 'password'))

context = ssl.create_default_context()
with smtplib.SMTP(host, port) as server:
    server.starttls(context=context)
    server.login(user, password)
    server.sendmail(user, ["recipient@example.com"], "Subject: Demo\n\nHello SMTP.")
```

## 5) 客户端使用（Node.js nodemailer）

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

```js
import fetch from 'node-fetch';
import nodemailer from 'nodemailer';

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

  const transporter = nodemailer.createTransport({
    host, port, secure: false,
    auth: { user, pass }
  });

  const info = await transporter.sendMail({
    from: user,
    to: 'recipient@example.com',
    subject: 'Demo',
    text: 'Hello SMTP'
  });
  console.log('Message sent:', info.messageId);
}

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

---

## 6) 要点

- SMTP 类型无典型 HTTP 登录，多数场景直接录入账号与密码即可；`responseMapping.source=direct` 表示无需请求，直接将表单值写入 Secret。
- 凭证使用阶段不需要构造 HTTP headers/query，故放入 `metadata.smtp`，由调用方选择邮件库实现。
- 若需要区分不同安全协议（SSL/TLS/STARTTLS），可在 `authFieldPlacements.metadata.smtp` 中再补充字段（如 `security: starttls`）。
