> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zappway.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Mail Inboxes API

> Internal reference for the Mail Inboxes API — inbox CRUD, forwarding address management, AI assignment, and inbound email processing.

> **Internal documentation for developers.** This page covers the Mail Inboxes API: creation, AI assignment, alias management, unread counts, and inbound email routing. Not intended for end users.

***

## Route Map

| Method   | Endpoint                                     | Handler File                                     | Description                        |
| -------- | -------------------------------------------- | ------------------------------------------------ | ---------------------------------- |
| `GET`    | `/api/mail-inboxes`                          | `mail-inboxes/route.ts`                          | List all mail inboxes              |
| `POST`   | `/api/mail-inboxes`                          | `mail-inboxes/route.ts`                          | Create a mail inbox                |
| `GET`    | `/api/mail-inboxes/[id]`                     | `mail-inboxes/[id]/route.ts`                     | Get inbox by ID                    |
| `PATCH`  | `/api/mail-inboxes/[id]`                     | `mail-inboxes/[id]/route.ts`                     | Update inbox (name, AI, knowledge) |
| `DELETE` | `/api/mail-inboxes/[id]`                     | `mail-inboxes/[id]/route.ts`                     | Delete inbox                       |
| `GET`    | `/api/mail-inboxes/unread`                   | `mail-inboxes/unread/route.ts`                   | Get unread counts per inbox        |
| `POST`   | `/api/mail-inboxes/check-alias-availability` | `mail-inboxes/check-alias-availability/route.ts` | Validate email alias               |

***

## Auth Pattern

```ts theme={null}
withPermissionRoute(req, {
  anyPermission: ['mail_inboxes.read'],  // reads
  anyPermission: ['mail_inboxes.manage'], // mutations
  authMode: 'lightweight',               // reads only
}, handler)
```

***

## Inbox Object Schema

```ts theme={null}
interface MailInbox {
  id: string;
  organizationId: string;
  name: string;
  alias: string;           // e.g., "a1b2c3d4" → a1b2c3d4@mail.zappway.ai
  agentId: string | null;  // assigned AI Employee
  aiEnabled: boolean;      // whether AI auto-responds
  datastoreIds: string[];  // connected knowledge
  datasourceIds: string[]; // connected knowledge
  createdAt: string;
  updatedAt: string;
}
```

***

## Alias Generation

When a new inbox is created, a unique alias is generated:

```ts theme={null}
// Format: {randomHex}@mail.zappway.ai
// Stored in: mail_inbox.alias
// Inbound emails sent to this address are processed by the inbox
```

**Alias availability check:**

```ts theme={null}
// POST /api/mail-inboxes/check-alias-availability
// Body: { alias: string }
// Returns: { available: boolean }
// Use before custom alias requests (if feature enabled)
```

***

## AI Assignment

```ts theme={null}
// PATCH /api/mail-inboxes/[id]
// Body: {
//   aiEnabled: true,
//   agentId: 'agent_123',
//   datastoreIds: ['ds_abc'],
//   datasourceIds: ['dsc_xyz'],
// }
```

When `aiEnabled: true` and `agentId` is set, every inbound email triggers the AI Employee to generate a response.

***

## Inbound Email Processing Flow

```
Email → Forwarded to {alias}@mail.zappway.ai
     ↓
ZappWay email receiving service (MX records)
     ↓
POST to internal webhook (not public API)
     ↓
Lookup inbox by alias
     ↓
Create contact (if new sender)
Create conversation (channel: 'email')
     ↓
If aiEnabled + agentId: trigger AI response
If aiEnabled + no agentId: queue for human
     ↓
AI response → sent via transactional email service
```

***

## Unread Counts

```ts theme={null}
// GET /api/mail-inboxes/unread
// Returns: { [inboxId]: number }
// Used by sidebar badge indicator
// authMode: 'lightweight' for performance
```

***

## Prisma Indexes Used

| Table       | Index            | Used by                  |
| ----------- | ---------------- | ------------------------ |
| `MailInbox` | `organizationId` | List inboxes             |
| `MailInbox` | `alias` (unique) | Inbound routing lookup   |
| `MailInbox` | `agentId`        | Agent assignment queries |

***

## Known Issues / Gotchas

* **Alias uniqueness:** `alias` must be globally unique across ALL organizations (not just within an org). The DB constraint is global.
* **Deleting an inbox:** Deleting doesn't revoke the email alias immediately — emails sent to a deleted alias will bounce. Consider a grace period or soft-delete.
* **AI response sender:** Emails are sent FROM `{alias}@mail.zappway.ai`, not from the customer's domain. This is a known limitation mentioned in user docs.
* **Knowledge source access:** `datastoreIds` and `datasourceIds` must belong to the same organization. Cross-org knowledge access is blocked by the permission layer.
