# Welcome

MailAgent is an AI-powered email assistant that helps you and your users manage email intelligently. It can automatically respond to emails, draft replies, classify messages, and integrate with external knowledge bases — all from within Gmail or your own website.

## What is MailAgent?

MailAgent consists of two main products:

### Chat Widget

An embeddable chat widget you can add to any website. Your visitors interact with an AI assistant that can draft and send emails, answer questions using your connected knowledge bases, and more.

> Perfect for customer support, sales teams, or any website that needs AI-powered email capabilities.

### Gmail Addon

A native Gmail sidebar addon that gives your users an AI copilot right inside their inbox. It can automatically respond to incoming emails, create drafts for review, classify messages with labels, and process individual email threads on demand.

> Ideal for teams that want hands-free email management with full control over AI behavior.

## Key Features

* **AI-Powered Responses** — Automatically draft or send email replies using advanced language models.
* **Custom Prompts** — Define exactly how the AI should behave with custom system prompts.
* **Draft Mode** — Review AI-generated responses before they're sent.
* **Email Classification** — Automatically label emails (e.g., "Answered", "Action Required").
* **MCP Integrations** — Connect external tools and APIs using the Model Context Protocol.
* **GitBook Integration** — Feed your product documentation as context for more accurate responses.
* **Email Signature** — Append a custom footer to all AI-generated emails.
* **Multi-Language Support** — 22+ languages supported out of the box.
* **Usage Quotas** — Built-in plan-based limits (Starter, Standard, Pro).

## Quick Links

| I want to...                   | Go to                                                   |
| ------------------------------ | ------------------------------------------------------- |
| Embed the widget on my website | [Widget — Getting Started](/widget/getting-started)     |
| Install the Gmail addon        | [Gmail Addon — Installation](/gmail-addon/installation) |
| Configure the AI agent         | [Gmail Addon — AI Agent](/gmail-addon/ai-agent)         |
| Connect my knowledge base      | [Gmail Addon — Integrations](/gmail-addon/integrations) |


# Overview

The MailAgent Gmail Addon brings AI-powered email assistance directly into your Gmail inbox as a sidebar. No context switching, no copy-pasting — just open an email and let the AI help.

## What It Does

When installed, the addon adds a sidebar panel to Gmail with the following capabilities:

* **AI Agent** — Toggle an autonomous AI that monitors your inbox and responds to emails automatically.
* **Draft Mode** — Choose whether the AI sends emails directly or creates drafts for your review.
* **Custom Prompt** — Define the AI's personality, tone, and behavior with a system prompt.
* **Email Labels** — Automatically classify and label processed emails.
* **Email Signature** — Append a custom footer to all AI-generated emails.
* **Integrations** — Connect MCP servers and GitBook knowledge bases for context-aware responses.
* **Process Email** — Manually trigger the AI to respond to the currently open email.
* **Quick Replies** — Get AI-suggested reply options when viewing an email.
* **Reports** — View email processing statistics.
* **User ID** — Your unique identifier, displayed at the bottom of the settings panel. You'll need this to [integrate the widget](/widget/getting-started).

## How It Works

```
┌─────────────────────────────────────────────┐
│  Gmail Inbox                                │
│  ┌────────────────────┐  ┌────────────────┐ │
│  │                    │  │  MailAgent      │ │
│  │   Email Thread     │  │  Sidebar       │ │
│  │                    │  │                │ │
│  │                    │  │  [AI Agent: ON] │ │
│  │                    │  │  Draft Mode     │ │
│  │                    │  │  Integrations   │ │
│  │                    │  │  Prompt         │ │
│  │                    │  │  Labels         │ │
│  │                    │  │  Signature      │ │
│  │                    │  │                │ │
│  └────────────────────┘  └────────────────┘ │
└─────────────────────────────────────────────┘
```

1. **Automatic Mode** — When the AI Agent is enabled, MailAgent watches for new unread emails via Gmail push notifications. For each new email, it reads the thread, generates a response using your configured prompt and integrations, and either sends the reply or creates a draft.
2. **Manual Mode** — When the AI Agent is disabled, you can still open any email and click "Process Email" to generate a response on demand. The addon will show the email's intent, quick reply suggestions, and a custom prompt field for generating replies.

## Subscription Plans

| Plan         | Daily Email Limit | Features          |
| ------------ | ----------------- | ----------------- |
| **Starter**  | 10 emails/day     | All core features |
| **Standard** | 50 emails/day     | All core features |
| **Pro**      | Unlimited         | All core features |

Your daily usage counter resets automatically every 24 hours.


# Installation

## Install from Google Workspace Marketplace

1. Go to the [MailAgent listing on Google Workspace Marketplace](https://workspace.google.com/marketplace).
2. Click **Install**.
3. Grant the required permissions when prompted.
4. Open Gmail — you'll see the MailAgent icon in the right sidebar.

## First-Time Setup

When you open the addon for the first time:

1. Click the **MailAgent icon** in the Gmail sidebar.
2. You'll be prompted to **authorize** the addon with your Google account.
3. Grant access to:
   * **Gmail** — Read and send emails on your behalf.
   * **Google Sheets** — For report generation.
4. Once authorized, the addon sidebar will load with all configuration options.

## Verify Installation

After installation, you should see:

* The MailAgent icon in the right sidebar of Gmail.
* When clicked, the sidebar shows the AI Agent switch and configuration sections.
* The AI Agent switch should be **off** by default.

## Troubleshooting

### Addon Not Appearing

* Refresh Gmail (`Ctrl+Shift+R` or `Cmd+Shift+R`).
* Check that the addon is enabled in **Settings > Add-ons**.
* Try signing out and back into Gmail.

### Authorization Error

* Ensure you've granted all required permissions.
* If you previously denied permissions, go to [myaccount.google.com/permissions](https://myaccount.google.com/permissions) to manage app access.

### Addon Loads but Shows an Error

* Check your internet connection.
* The MailAgent backend may be temporarily unavailable — wait a moment and retry.
* If the issue persists, contact support.


# AI Agent

The AI Agent is the core feature of MailAgent. When enabled, it autonomously monitors your inbox for new emails and generates responses based on your configuration.

## Enabling the Agent

At the top of the MailAgent sidebar, you'll find the **AI Agent** toggle switch:

* **ON** — The agent actively watches for new unread emails and responds automatically.
* **OFF** — The agent is inactive. You can still process emails manually.

## How It Works

When the AI Agent is enabled:

1. **Gmail Push Notifications** — Gmail sends a notification to MailAgent whenever a new email arrives.
2. **Thread Analysis** — The agent reads the full email thread for context.
3. **Response Generation** — Using your configured system prompt, integrations, and email history, the AI generates an appropriate response.
4. **Action** — Depending on your [Draft Mode](/gmail-addon/draft-mode) setting:
   * **Draft Mode ON** — A draft is created for your review.
   * **Draft Mode OFF** — The email is sent automatically.
5. **Labeling** — The email is labeled according to your [Email Labels](/gmail-addon/email-labels) configuration.

## Daily Limits

Your subscription plan determines how many emails the agent can process per day:

| Plan     | Daily Limit |
| -------- | ----------- |
| Starter  | 10          |
| Standard | 50          |
| Pro      | Unlimited   |

The current usage count is displayed below the agent toggle. When you reach your limit:

* The agent will stop processing new emails.
* You'll see a notification with your current usage.
* The counter resets automatically every 24 hours.

## Best Practices

* **Start with Draft Mode ON** — Review the AI's responses before letting it send emails directly. This helps you fine-tune the system prompt.
* **Write a clear system prompt** — The more specific your [Custom Prompt](/gmail-addon/custom-prompt), the better the AI's responses will match your expectations.
* **Connect knowledge bases** — Add [GitBook integrations](/gmail-addon/integrations) so the AI can reference your product documentation for accurate answers.
* **Use classification labels** — Set up [Email Labels](/gmail-addon/email-labels) so you can easily track what the agent has handled.

## Automatic Deactivation

The agent will automatically disable itself if:

* Your Google OAuth token expires and cannot be refreshed.
* Your daily email limit is reached.
* There is a persistent authentication error.

When this happens, you'll need to re-enable the agent manually from the sidebar.


# Draft Mode

Draft Mode controls whether the AI agent sends emails directly or creates drafts for you to review first.

## How to Enable

1. Open the MailAgent sidebar in Gmail.
2. Click **Draft Mode**.
3. Toggle the switch ON or OFF.

## Behavior

| Setting | Behavior                                                                             |
| ------- | ------------------------------------------------------------------------------------ |
| **ON**  | The AI creates a draft in your Gmail Drafts folder. You review and send it manually. |
| **OFF** | The AI sends the email immediately on your behalf.                                   |

## When to Use Draft Mode

**Enable Draft Mode when:**

* You're first setting up MailAgent and want to verify the AI's responses.
* You're handling sensitive communications that require human review.
* You want to edit or personalize AI-generated responses before sending.
* You're fine-tuning your system prompt and want to see the results.

**Disable Draft Mode when:**

* You're confident in the AI's response quality.
* You're handling high-volume, low-risk emails (e.g., support acknowledgments).
* Speed of response is critical.

## Finding Your Drafts

When Draft Mode is on, AI-generated drafts appear in your standard Gmail **Drafts** folder. Each draft:

* Is pre-addressed to the correct recipient.
* Contains the AI-generated response body.
* Includes your configured [Email Signature](/gmail-addon/email-signature) (if set).
* Is part of the correct email thread.

You can edit the draft as needed before sending.


# Custom Prompt

The Custom Prompt defines the AI agent's behavior, personality, and response style. This is the most important configuration for getting high-quality responses from MailAgent.

## Setting Your Prompt

1. Open the MailAgent sidebar in Gmail.
2. Click **Prompt**.
3. Enter your system prompt in the text area.
4. Save.

## What is a System Prompt?

A system prompt is a set of instructions that tells the AI how to behave. It's applied to every email the agent processes. Think of it as the AI's "job description."

## Examples

### Customer Support Agent

```
You are a friendly customer support agent for Acme Corp.

Rules:
- Always greet the customer by name.
- Be empathetic and professional.
- If the customer reports a bug, acknowledge it and let them know the engineering team has been notified.
- For billing questions, direct them to billing@acme.com.
- Keep responses concise — no more than 3 paragraphs.
- Sign off with "Best regards, Acme Support Team".
```

### Executive Assistant

```
You are an executive assistant managing emails for the CEO.

Rules:
- Be formal and professional.
- For meeting requests, confirm availability and suggest times.
- For partnership inquiries, express interest and offer to schedule a call.
- For cold sales emails, politely decline.
- Prioritize brevity — executives are busy.
- Never commit to deadlines or pricing without explicit instruction.
```

### Technical Support

```
You are a technical support specialist for a SaaS platform.

Rules:
- Identify the technical issue from the email.
- Provide step-by-step troubleshooting instructions when possible.
- Reference documentation links when relevant.
- If the issue requires escalation, let the user know a senior engineer will follow up.
- Use clear, non-jargon language.
```

## Tool-Specific Prompts

In addition to the main system prompt, you can set prompts for specific tools. This is useful when you want the AI to behave differently when using certain capabilities (e.g., sending emails vs. looking up documentation).

1. Open the MailAgent sidebar.
2. Click **Prompt**.
3. Select the specific tool from the tools list.
4. Enter a tool-specific prompt.

## Tips for Writing Effective Prompts

* **Be specific** — Vague prompts lead to generic responses. Tell the AI exactly what you want.
* **Set boundaries** — Specify what the AI should NOT do (e.g., "Never share pricing information").
* **Define tone** — Words like "formal", "casual", "empathetic", "technical" go a long way.
* **Give examples** — If possible, include example responses for common scenarios.
* **Iterate** — Use [Draft Mode](/gmail-addon/draft-mode) to review responses and refine your prompt over time.


# Email Labels

MailAgent can automatically apply Gmail labels to emails after processing them. This helps you track which emails the AI has handled and what action was taken.

## Default Labels

When you enable the AI agent, MailAgent creates two labels in your Gmail:

| Label               | Meaning                                               |
| ------------------- | ----------------------------------------------------- |
| **Answered**        | The AI has sent a response (or created a draft).      |
| **Action Required** | The AI flagged this email as needing human attention. |

## Configuring Labels

1. Open the MailAgent sidebar in Gmail.
2. Click **Labels**.
3. Select which Gmail labels to use for classification.
4. Save.

You can use any existing Gmail label or let MailAgent create new ones.

## Classification Labels

Beyond the default labels, you can define custom classification labels. The AI will analyze the email content and apply the most appropriate label.

Common classification schemes:

* **By Priority:** Urgent, Normal, Low Priority
* **By Department:** Sales, Support, Billing, Engineering
* **By Action:** Needs Reply, FYI Only, Requires Approval
* **By Topic:** Bug Report, Feature Request, General Inquiry

## How Classification Works

1. The AI reads the incoming email.
2. Based on the email content and your configured labels, it determines the appropriate classification.
3. The label is applied to the email in Gmail.
4. The response label ("Answered" or "Action Required") is also applied.

## Tips

* Keep your label set manageable — 5-10 classification labels work best.
* Use descriptive label names so the AI can match emails accurately.
* Review classifications periodically and adjust your [Custom Prompt](/gmail-addon/custom-prompt) if the AI is miscategorizing.


# Email Signature

Add a custom footer to all AI-generated emails. This is useful for disclaimers, contact information, or branding.

## Setting Your Signature

1. Open the MailAgent sidebar in Gmail.
2. Click **Signature**.
3. Enter your footer text.
4. Save.

## Examples

### Simple

```
Best regards,
John Doe
Acme Corp
```

### With Contact Info

```
---
Jane Smith | Head of Support
Acme Corp | jane@acme.com
Phone: +1 (555) 123-4567
```

### With Disclaimer

```
---
This email was composed with AI assistance.
Acme Corp | acme.com
```

## How It Works

The footer is appended to the end of every email the AI generates, whether sent directly or saved as a draft. It's added after the AI's response body.

> **Note:** The signature set in MailAgent is separate from your Gmail signature. Both will appear in the final email if you have a Gmail signature configured. Consider disabling your Gmail signature for the AI-managed account to avoid duplication.


# Integrations

MailAgent supports external integrations that give the AI access to additional context and tools when composing responses. This makes responses more accurate and relevant.

## Available Integrations

### GitBook

Connect your GitBook documentation so the AI can reference your product docs when answering emails.

**Setup:**

1. Open the MailAgent sidebar in Gmail.
2. Click **Integrations**.
3. Click **GitBook**.
4. Enter your GitBook space URL.
5. Save.

Once connected, the AI will search your documentation for relevant information before composing a response. This is especially useful for:

* Customer support — AI can reference product guides and FAQs.
* Technical support — AI can link to API docs and troubleshooting guides.
* Sales — AI can reference feature pages and pricing information.

A green checkmark appears next to GitBook in the integrations list when connected.

### MCP Servers (Model Context Protocol)

Connect any MCP-compatible server to extend the AI's capabilities with custom tools and data sources.

**What is MCP?**

The Model Context Protocol is an open standard for connecting AI models to external tools and data. MCP servers expose capabilities that the AI can invoke during email composition.

**Setup:**

1. Open the MailAgent sidebar in Gmail.
2. Click **Integrations**.
3. Click **MCP**.
4. Enter the MCP server URL (must be an HTTP endpoint).
5. Optionally add a Bearer token for authentication.
6. Save.

**Examples of MCP servers:**

* **CRM integration** — Look up customer information before responding.
* **Knowledge base** — Search internal wikis or documentation.
* **Order system** — Check order status to include in responses.
* **Calendar** — Check availability for scheduling emails.

A green checkmark appears next to MCP in the integrations list when at least one server is connected.

## Managing Integrations

You can add multiple MCP servers and connect multiple knowledge bases. To remove an integration:

1. Open the MailAgent sidebar.
2. Click **Integrations**.
3. Navigate to the integration you want to remove.
4. Click Remove / Disconnect.

## How Integrations Affect Responses

When the AI processes an email:

1. It analyzes the email content and determines what context might be needed.
2. If relevant, it queries connected integrations (GitBook docs, MCP tools).
3. The retrieved information is used as additional context for generating the response.
4. The final email incorporates both the AI's knowledge and the integration data.

This means the AI's responses become more accurate and specific to your business as you add more integrations.


# Process Email

Process Email lets you manually trigger the AI to respond to a specific email, without needing the AI Agent to be enabled.

## How to Use

1. Open an email in Gmail.
2. The MailAgent sidebar will detect the open email.
3. Click the **Process Email** button.
4. The AI will read the thread, generate a response, and either send it or create a draft (depending on your [Draft Mode](/gmail-addon/draft-mode) setting).

## When the AI Agent is Disabled

When the AI Agent toggle is off, opening an email shows an enhanced view with:

### Email Intent

A brief summary of what the sender is asking for or communicating. This helps you quickly understand the email without reading the full thread.

### Quick Replies

AI-generated reply suggestions based on the email content. Each suggestion shows:

* A preview of the response.
* A **Use** button to create a draft with that response.

Quick replies are great for:

* Common questions with standard answers.
* Acknowledgment emails.
* Simple yes/no responses.

### Custom Reply

If the quick replies don't fit, use the custom prompt field:

1. Enter a description of what you want the reply to say.
2. Click **Generate Reply**.
3. The AI generates a draft based on your instructions and the email context.

The field also shows **suggestions** based on the email content to help you get started.

## When the AI Agent is Enabled

When the AI Agent is on, the sidebar shows a simplified view with just the **Process Email** button. This is useful for:

* Forcing the agent to reprocess an email it already handled.
* Processing an email that arrived before the agent was enabled.
* Generating a response for an email the agent skipped.

## Out of Credits

If you've reached your daily email limit, the Process Email view will display a notification with an option to view your subscription plan and upgrade.


# Getting Started

Add the MailAgent chat widget to your website in under 5 minutes. Your users will be able to interact with an AI assistant that can draft emails, answer questions, and more.

## Prerequisites

* A MailAgent account with a **user ID**
* A website where you can add a `<script>` tag

## Quick Start

Add the following script tag to your HTML:

```html
<script
  src="https://widget.mailagent.email/connect/connect.js"
  data-user-id="YOUR_USER_ID"
></script>
```

Then open the widget from JavaScript:

```javascript
const widget = await MailAgent.open({
  bottom: "20px",
  right: "20px",
  width: "400px",
  height: "600px"
});
```

That's it. The widget will appear as a fixed-position chat window in the corner of your page.

## Finding Your User ID

The `data-user-id` is your MailAgent user ID — the unique identifier assigned to your account when you sign in with Google.

### From the Gmail Addon

The easiest way to find your user ID is in the Gmail addon:

1. Open Gmail and click the MailAgent icon in the sidebar.
2. Scroll to the bottom of the settings panel.
3. Your user ID is displayed under **"Your User ID"**.

## What Happens Under the Hood

1. The `connect.js` script loads and registers the global `MailAgent` object on `window`.
2. When you call `MailAgent.open()`, it creates a sandboxed `<iframe>` pointing to the MailAgent hosted app.
3. The iframe initializes with your user ID and configuration via `postMessage`.
4. Once ready, the widget fades in and your users can start chatting.

## Next Steps

* [Installation](/widget/installation) — All the ways to add the widget to your site.
* [Configuration](/widget/configuration) — Customize suggestions, colors, and header.
* [JavaScript API](/widget/javascript-api) — Control the widget programmatically.


# Installation

## Script Tag (Recommended)

The simplest way to add MailAgent to your website is with a single `<script>` tag. Place it before the closing `</body>` tag:

```html
<script
  src="https://widget.mailagent.email/connect/connect.js"
  data-user-id="YOUR_USER_ID"
></script>
```

This registers the global `window.MailAgent` object. You can then open the widget from anywhere in your code.

### With Configuration

Pass configuration directly via `data-*` attributes on the script tag:

```html
<script
  src="https://widget.mailagent.email/connect/connect.js"
  data-user-id="YOUR_USER_ID"
  data-suggestions='[
    {"icon": "✉️", "text": "Write a professional email"},
    {"icon": "📝", "text": "Summarize this thread"}
  ]'
  data-header-transparent="true"
  data-color-background-primary="#2c7df6"
></script>
```

## Single Page Applications (React, Vue, Next.js, etc.)

For SPAs, add the script tag to your root HTML file (`index.html`, `_document.tsx`, etc.) or load it dynamically:

```javascript
// Load the connect script dynamically
const script = document.createElement('script');
script.src = 'https://widget.mailagent.email/connect/connect.js';
script.dataset.userId = 'YOUR_USER_ID';
document.body.appendChild(script);
```

### React Example

```tsx
import { useEffect, useRef } from 'react';

function ChatWidget() {
  const widgetRef = useRef(null);

  const openChat = async () => {
    if (widgetRef.current?.mounted) return;

    widgetRef.current = await MailAgent.open({
      bottom: '20px',
      right: '20px',
      width: '400px',
      height: '600px',
    });
  };

  return <button onClick={openChat}>Open Chat</button>;
}
```

### Next.js Example

Add the script in `app/layout.tsx` or `pages/_document.tsx`:

```tsx
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Script
          src="https://widget.mailagent.email/connect/connect.js"
          data-user-id="YOUR_USER_ID"
          strategy="afterInteractive"
        />
      </body>
    </html>
  );
}
```

## Verify Installation

Open your browser's developer console and type:

```javascript
typeof window.MailAgent // should return "object"
```

If it returns `"object"`, the widget is loaded and ready to use.


# Configuration

The widget can be configured in two ways: via **data attributes** on the script tag (static config) and via the **JavaScript API** when opening the widget (dynamic config).

## Script Tag Attributes

These are set as `data-*` attributes on the `<script>` tag and apply globally.

| Attribute                       | Type      | Required | Description                                     |
| ------------------------------- | --------- | -------- | ----------------------------------------------- |
| `data-user-id`                  | `string`  | Yes      | Your MailAgent user ID.                         |
| `data-suggestions`              | `JSON`    | No       | Array of quick-action suggestions.              |
| `data-header-transparent`       | `boolean` | No       | Set to `"true"` to make the header transparent. |
| `data-color-background-primary` | `string`  | No       | Primary background color (hex code).            |

### Suggestions Format

Suggestions appear as clickable quick-action buttons in the chat. Each suggestion has an icon and text:

```html
<script
  src="https://widget.mailagent.email/connect/connect.js"
  data-user-id="YOUR_USER_ID"
  data-suggestions='[
    {"icon": "✉️", "text": "Write a professional email"},
    {"icon": "📝", "text": "Summarize this thread"},
    {"icon": "🔍", "text": "Find relevant information"},
    {"icon": "💬", "text": "Draft a reply"}
  ]'
></script>
```

| Field  | Type     | Required | Description                                              |
| ------ | -------- | -------- | -------------------------------------------------------- |
| `icon` | `string` | No       | An emoji or short string shown as icon.                  |
| `text` | `string` | Yes      | The suggestion text (also sent as message when clicked). |

## Open Options

These are passed to `MailAgent.open()` and can differ each time the widget is opened:

```javascript
const widget = await MailAgent.open({
  path: "/",
  top: "20px",
  right: "20px",
  width: "400px",
  height: "600px",
  distinctId: "user_analytics_id"
});
```

| Option       | Type     | Default | Description                                                                 |
| ------------ | -------- | ------- | --------------------------------------------------------------------------- |
| `path`       | `string` | `"/"`   | Route within the widget (e.g., `"/"` for chat, `"/feedback"` for feedback). |
| `top`        | `string` | —       | CSS `top` position (e.g., `"20px"`).                                        |
| `left`       | `string` | —       | CSS `left` position.                                                        |
| `right`      | `string` | —       | CSS `right` position.                                                       |
| `bottom`     | `string` | —       | CSS `bottom` position.                                                      |
| `width`      | `string` | —       | Fixed width. Omit for auto-resize.                                          |
| `height`     | `string` | —       | Fixed height. Omit for auto-resize.                                         |
| `distinctId` | `string` | —       | Analytics identifier for the current visitor.                               |

### Auto-Resize

If you omit `width` and `height`, the widget will automatically resize to fit its content. The widget communicates its dimensions to the parent page via `postMessage`.

```javascript
// Auto-resize mode — widget adjusts to content
const widget = await MailAgent.open({
  bottom: "20px",
  right: "20px"
});
```

### Fixed Size

If you provide both `width` and `height`, the widget will be fixed at those dimensions with internal scrolling.

```javascript
// Fixed size mode
const widget = await MailAgent.open({
  bottom: "20px",
  right: "20px",
  width: "400px",
  height: "600px"
});
```


# JavaScript API

The widget exposes a global `window.MailAgent` object with methods to open, control, and close the widget programmatically.

## `MailAgent.open(options)`

Opens the widget and returns a handle for interacting with it.

```javascript
const widget = await MailAgent.open({
  bottom: "20px",
  right: "20px",
  width: "400px",
  height: "600px"
});
```

**Returns:** `Promise<WidgetHandle>`

See [Configuration](/widget/configuration) for all available options.

## Widget Handle

The object returned by `MailAgent.open()` provides the following interface:

### `widget.send(message)`

Send a message to the chat programmatically. This triggers the AI assistant to respond as if the user typed the message.

```javascript
// Send a text message
widget.send({ text: "Draft a follow-up email to the client" });
```

```javascript
// Send with file attachments
widget.send({
  text: "Summarize this document",
  files: [file]
});
```

### `widget.mounted`

A read-only boolean indicating whether the widget iframe is still attached to the DOM.

```javascript
if (widget.mounted) {
  widget.send({ text: "Hello!" });
}
```

### `widget.unmount()`

Closes and removes the widget from the page with a fade-out animation.

```javascript
widget.unmount();
```

## Full Example

```html
<!DOCTYPE html>
<html>
<head>
  <title>My App</title>
</head>
<body>
  <button id="open-chat">Open Chat</button>
  <button id="close-chat" disabled>Close Chat</button>
  <button id="send-msg" disabled>Ask about pricing</button>

  <script
    src="https://widget.mailagent.email/connect/connect.js"
    data-user-id="YOUR_USER_ID"
    data-suggestions='[{"icon":"💬","text":"Help me write an email"}]'
  ></script>

  <script>
    let widget = null;

    document.getElementById('open-chat').addEventListener('click', async () => {
      widget = await MailAgent.open({
        bottom: '20px',
        right: '20px',
        width: '400px',
        height: '600px',
      });

      document.getElementById('close-chat').disabled = false;
      document.getElementById('send-msg').disabled = false;
    });

    document.getElementById('close-chat').addEventListener('click', () => {
      widget?.unmount();
      widget = null;
      document.getElementById('close-chat').disabled = true;
      document.getElementById('send-msg').disabled = true;
    });

    document.getElementById('send-msg').addEventListener('click', () => {
      widget?.send({ text: 'What are your pricing plans?' });
    });
  </script>
</body>
</html>
```

## Events

The widget communicates with the parent page via `postMessage`. You can listen for these events if you need deeper integration:

| Event Type          | Direction       | Description                            |
| ------------------- | --------------- | -------------------------------------- |
| `init`              | Parent ← Widget | Widget requests initialization data.   |
| `init`              | Parent → Widget | Parent sends config (userId, etc.).    |
| `initialized`       | Parent ← Widget | Widget is fully loaded and ready.      |
| `__widget_resize__` | Parent ← Widget | Widget reports its content dimensions. |
| `close`             | Parent ← Widget | Widget requests to be closed.          |
| `send`              | Parent → Widget | Parent sends a message to the chat.    |

> **Note:** You typically don't need to handle these events directly — the `MailAgent.open()` API manages them for you. These are documented for advanced use cases only.


# Styling & Theming

The widget runs inside a sandboxed iframe, so it won't conflict with your page styles. You can customize its appearance through configuration options.

## Primary Color

Set the primary background color using the `data-color-background-primary` attribute:

```html
<script
  src="https://widget.mailagent.email/connect/connect.js"
  data-user-id="YOUR_USER_ID"
  data-color-background-primary="#2c7df6"
></script>
```

This color is applied to:

* The header background
* Primary buttons
* Active state indicators
* Message accent elements

## Transparent Header

Make the header blend with the chat background:

```html
<script
  src="https://widget.mailagent.email/connect/connect.js"
  data-user-id="YOUR_USER_ID"
  data-header-transparent="true"
></script>
```

This is useful when embedding the widget in a context where you want a cleaner, more integrated look.

## Positioning

Control where the widget appears on screen via CSS position properties:

```javascript
// Bottom-right corner (common for support widgets)
await MailAgent.open({
  bottom: "20px",
  right: "20px",
  width: "400px",
  height: "600px"
});

// Centered on page
await MailAgent.open({
  top: "50%",
  left: "50%",
  width: "500px",
  height: "700px"
});

// Full sidebar
await MailAgent.open({
  top: "0",
  right: "0",
  width: "400px",
  height: "100vh"
});
```

The widget is rendered with `position: fixed` and `z-index: 9999`, so it will float above your page content.

## Iframe Styling

The widget iframe has the following default styles:

* No border
* Transparent background
* Hidden overflow
* Fade-in animation on load (200ms ease)

Since it's an iframe, you cannot inject CSS into the widget from your page. All theming must go through the configuration options described above.


# Advanced Usage

## Multiple Widget Instances

You can open multiple widget instances simultaneously, each with different configurations:

```javascript
const supportWidget = await MailAgent.open({
  bottom: "20px",
  right: "20px",
  width: "350px",
  height: "500px"
});

const feedbackWidget = await MailAgent.open({
  path: "/feedback",
  bottom: "20px",
  left: "20px",
  width: "350px",
  height: "400px"
});
```

## Dynamic User Switching

If your application supports multiple users or accounts, load the script once and pass different user IDs when opening:

```javascript
// The data-user-id on the script tag is the default.
// You can override it in the init flow via postMessage if needed.
```

## Analytics Integration

Pass a `distinctId` to associate widget analytics with your own user tracking:

```javascript
const widget = await MailAgent.open({
  bottom: "20px",
  right: "20px",
  width: "400px",
  height: "600px",
  distinctId: currentUser.analyticsId
});
```

This ID is forwarded to the analytics system (PostHog) so you can correlate widget usage with your own user metrics.

## Programmatic Messaging

Use `widget.send()` to trigger contextual conversations based on user actions in your app:

```javascript
// User clicks a "Help" button next to an order
widget.send({
  text: `Help me write a follow-up email about order #${orderId}`
});

// User selects a template
widget.send({
  text: "Draft an email using the 'Meeting Request' template"
});
```

## Lifecycle Management

The widget handle gives you control over the widget lifecycle:

```javascript
const widget = await MailAgent.open({ /* ... */ });

// Check if still in DOM
console.log(widget.mounted); // true

// Close the widget
widget.unmount();

// After unmount completes
console.log(widget.mounted); // false
```

The `unmount()` method plays a fade-out animation before removing the iframe. The widget handle becomes invalid after unmounting.

## Chat Persistence

The widget automatically persists chat history in the browser using `localForage`. Messages are stored for **24 hours** and will be restored if the user reopens the widget within that window.

This means:

* Users can close and reopen the widget without losing context.
* Refreshing the page preserves the conversation.
* After 24 hours, the chat history is automatically cleared.

## Feedback Page

The widget includes a built-in feedback page at the `/feedback` route:

```javascript
const feedbackWidget = await MailAgent.open({
  path: "/feedback",
  bottom: "20px",
  right: "20px",
  width: "400px",
  height: "500px"
});
```

## Language Detection

The widget automatically detects the user's browser language (`navigator.language`) and sends it with each message. The AI assistant will respond in the same language when possible. 22+ languages are supported, including:

English, Spanish, French, German, Arabic, Chinese, Japanese, Korean, Portuguese, Russian, Italian, Dutch, Polish, Turkish, Vietnamese, Thai, Indonesian, Hindi, Bengali, Swedish, Danish, and Norwegian.


