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

# CLI

> Generate, send, validate, and export emails from the terminal; manage contacts, segments, domains, and webhooks.

The Migma CLI wraps the full API into terminal commands. Use it for quick workflows, scripting, CI/CD pipelines, or anywhere you'd rather type than code.

<CodeGroup>
  ```bash Install script theme={null}
  curl -fsSL https://install.migma.ai/cli | sh
  ```

  ```bash npm theme={null}
  npm install -g @migma/cli
  ```

  ```bash yarn theme={null}
  yarn global add @migma/cli
  ```

  ```bash pnpm theme={null}
  pnpm add -g @migma/cli
  ```

  ```bash npx (no install) theme={null}
  npx @migma/cli --help
  ```
</CodeGroup>

**Requires** Node.js 18+.

***

## Quick start

Five commands to go from zero to a sent email:

```bash theme={null}
# 1. Authenticate
migma login

# 2. Import your brand
migma projects import https://yourbrand.com --wait

# 3. Set it as default
migma projects use <projectId>

# 4. Generate an email and note the printed email ID
migma generate "Welcome email for new subscribers" --wait

# 5. Send the generated email
migma send --to sarah@example.com --email <emailId> \
  --subject "Welcome!" --from hello@yourbrand.migma.email --from-name "Your Brand"
```

***

## Authentication

```bash theme={null}
migma login
```

You'll be prompted for your API key. Get one from [Settings → Developers → API Keys](https://migma.ai/settings?tab=api-keys).

You can also set the `MIGMA_API_KEY` environment variable — the CLI checks it first, then falls back to the stored config.

```bash theme={null}
export MIGMA_API_KEY=your_migma_api_key
```

| Command        | Description                            |
| -------------- | -------------------------------------- |
| `migma login`  | Save your API key (interactive prompt) |
| `migma logout` | Remove stored credentials              |
| `migma whoami` | Show current key and default project   |

***

## Generate

Create on-brand emails with AI from a single command.

```bash theme={null}
migma generate "Summer sale — 30% off everything" --wait
```

| Flag               | Effect                                              |
| ------------------ | --------------------------------------------------- |
| `--wait`           | Block until generation completes                    |
| `--save <file>`    | Save the finished HTML locally (requires `--wait`)  |
| `--open`           | Open the result in your browser (requires `--wait`) |
| `--image <url>`    | Attach a reference image to the prompt              |
| `--reference <id>` | Remix from an existing conversation ID              |
| `--count <n>`      | Request a specific number of emails for a series    |

<Tip>
  Chain with validate: `migma generate "..." --wait && migma validate all --conversation <conversationId>`
</Tip>

Create a series and save each email as a separate HTML file:

```bash theme={null}
migma generate "Three-email onboarding series for new trial users" --count 3 --wait --save ./onboarding.html
```

When a generation returns multiple emails, `--save ./onboarding.html` writes `onboarding-1.html`, `onboarding-2.html`, and so on. The status output also lists each email ID, which you use to fetch, edit, or send that email.

Check on a running generation:

```bash theme={null}
migma generate-status <conversationId>
```

***

## Send

Send to an individual, a segment, or a tag. Emails send through Migma by default — you can also connect [external providers](/integrations/email-service-providers).

<CodeGroup>
  ```bash Individual theme={null}
  migma send \
    --to sarah@example.com \
    --email email_abc123 \
    --from hello@yourbrand.migma.email \
    --from-name "Your Brand" \
    --subject "Your discount inside"
  ```

  ```bash To a segment theme={null}
  migma send \
    --segment seg_vip \
    --email email_abc123 \
    --subject "Exclusive VIP Offer" \
    --from hello@yourbrand.migma.email \
    --from-name "Your Brand"
  ```
</CodeGroup>

Use `--email` with the email ID returned by generation status or selected in the editor, especially multi-slot emails and series. `--from-conversation` works for single-email conversations.

| Command                                          | Description                   |
| ------------------------------------------------ | ----------------------------- |
| `migma send-test --email <emailId> --to <email>` | Send a test email             |
| `migma batch-status <batchId>`                   | Check batch delivery progress |

<Tip>
  Add `--idempotency-key <key>` to `send` to make a retry safe: sending the same key with the same body within 24 hours replays the original response instead of sending twice. Use a deterministic key you can reproduce on retry (for example `send-<emailId>-<recipient>`), never a random value or timestamp.
</Tip>

***

## Validate

Run [preflight checks](/email-editor/email-preflight) before you send.

```bash theme={null}
migma validate all --html ./email.html
```

| Check                           | What it does                                                    |
| ------------------------------- | --------------------------------------------------------------- |
| `migma validate all`            | Run every check, show overall score                             |
| `migma validate compatibility`  | Compatibility report for major email clients (score out of 100) |
| `migma validate links`          | Find broken links                                               |
| `migma validate spelling`       | Grammar and spelling                                            |
| `migma validate deliverability` | Spam score and inbox prediction                                 |

All commands accept `--html <file>` or `--conversation <id>`.

***

## Export

Export generated emails to files or platforms. See [export options](/email-editor/export-options) for details on each format.

```bash theme={null}
# Save HTML locally
migma export html conv_abc123 --output ./email.html

# Export for Klaviyo
migma export klaviyo conv_abc123 --type hybrid
```

| Format    | Command                       |
| --------- | ----------------------------- |
| HTML      | `migma export html <id>`      |
| MJML      | `migma export mjml <id>`      |
| PDF       | `migma export pdf <id>`       |
| Klaviyo   | `migma export klaviyo <id>`   |
| Mailchimp | `migma export mailchimp <id>` |
| HubSpot   | `migma export hubspot <id>`   |

All export commands support `--output <file>` to download the result locally.

***

## Campaigns

Create and manage marketing campaigns with lifecycle tracking (create, schedule, send, cancel).

<Note>
  **Campaigns vs `migma send`:** Use `migma send` for quick fire-and-forget sends (transactional emails, one-off blasts). Use `migma campaigns` when you need a named, trackable campaign tied to a project — with scheduling, status tracking, and recipient counts.
</Note>

```bash theme={null}
# Create a campaign from a generated email
migma campaigns create --project <projectId> \
  --name "Investor Update" --conversation <conversationId> --email <emailId> \
  --from hello@company.migma.email --from-name "Company" \
  --recipient-type tag --recipient-id <tagId>

# Send immediately
migma campaigns send <campaignId>

# Or schedule for later
migma campaigns schedule <campaignId> --at "2026-03-15T14:00:00Z" --timezone "America/New_York"

# Cancel a scheduled campaign
migma campaigns cancel <campaignId>

# Engagement stats and per-recipient delivery logs
migma campaigns stats <campaignId>
migma campaigns logs <campaignId> --status bounced --limit 50
```

| Command                                                                                                                                                             | Description                                                       |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| `migma campaigns list`                                                                                                                                              | List campaigns for a project                                      |
| `migma campaigns create --name <name> --conversation <conversationId> --email <emailId> --from <email> --from-name <name> --recipient-type tag --recipient-id <id>` | Create a campaign from a generated email                          |
| `migma campaigns get <id>`                                                                                                                                          | Get campaign details                                              |
| `migma campaigns send <id>`                                                                                                                                         | Send a campaign immediately                                       |
| `migma campaigns schedule <id> --at <datetime>`                                                                                                                     | Schedule for future delivery                                      |
| `migma campaigns cancel <id>`                                                                                                                                       | Cancel a scheduled campaign                                       |
| `migma campaigns stats <id>`                                                                                                                                        | Engagement stats (sent, delivered, opens, clicks, bounces, rates) |
| `migma campaigns logs <id> [--status <s>] [--limit <n>] [--cursor <c>]`                                                                                             | Per-recipient delivery logs, cursor-paginated                     |

`campaigns logs` accepts `--status` (`delivered`, `opened`, `clicked`, `bounced`, `spam_report`), `--limit` (1-100), and `--cursor` for the next page. Stats come from the tracking worker and may be slightly stale; `botOpens`, `botClicks`, and `mppOpens` reflect Apple Mail Privacy Protection and bot detection when available.

<Tip>
  `campaigns create`, `campaigns send`, and `campaigns schedule` all accept `--idempotency-key <key>` for safe retries. The same key with the same body within 24 hours replays the original response. For campaign sends, a deterministic key like `campaign-send-<campaignId>` prevents a retried send from going out twice. Don't use a random value or timestamp.
</Tip>

***

## Emails

List, fetch, and prompt-edit your generated emails.

```bash theme={null}
migma emails list --project <projectId>
migma emails get <emailId> --output ./email.html
migma emails edit <emailId> --prompt "Make this welcome email shorter" --output ./email.html
migma emails metrics <emailId>
migma emails logs <emailId> --status opened --limit 50
```

| Command                                                                   | Description                                                                                        |
| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `migma emails list`                                                       | List emails for a project (paginated)                                                              |
| `migma emails get <emailId>`                                              | Get one generated email with production HTML                                                       |
| `migma emails edit <emailId> --prompt <text>`                             | Prompt Migma to edit one generated email                                                           |
| `migma emails metrics <emailId>`                                          | Performance for one generated email across its API sends (delivery, opens, clicks, bounces, rates) |
| `migma emails logs <emailId> [--status <s>] [--limit <n>] [--cursor <c>]` | Per-recipient send log for one generated email, cursor-paginated                                   |

`emails logs` accepts `--status` (`delivered`, `opened`, `clicked`, `bounced`, `complained`, `suppressed`, `sent`), `--limit` (1-100), and `--cursor` for the next page. Stats come from the tracking worker and may be slightly stale; opens are directional (Apple Mail Privacy Protection and bots inflate them) while clicks and delivery are stronger signals.

| Flag                | Effect                                                            |
| ------------------- | ----------------------------------------------------------------- |
| `--limit <n>`       | Max results (1-100, default 20)                                   |
| `--status <status>` | Filter by status (`pending`, `processing`, `completed`, `failed`) |
| `--search <query>`  | Search by title or subject                                        |

***

## Audience

<AccordionGroup>
  <Accordion title="Contacts" icon="address-book">
    | Command                                                  | Description               |
    | -------------------------------------------------------- | ------------------------- |
    | `migma contacts list`                                    | List contacts (paginated) |
    | `migma contacts add --email <email> --status subscribed` | Create a contact          |
    | `migma contacts get <id>`                                | Get contact details       |
    | `migma contacts update <id> --first-name Jane`           | Update a contact          |
    | `migma contacts remove <id>`                             | Delete a contact          |
    | `migma contacts import ./file.csv`                       | Bulk import from CSV      |

    The CSV importer auto-detects common column names (`email`, `firstName`, `first_name`, `First Name`, etc.). Any unrecognized columns become custom fields.

    `contacts add` accepts `--idempotency-key <key>` so a retried create won't duplicate the contact: the same key with the same body within 24 hours replays the original response. A deterministic key like `contact-<email>` works well.
  </Accordion>

  <Accordion title="Tags" icon="tag">
    | Command                          | Description   |
    | -------------------------------- | ------------- |
    | `migma tags list`                | List all tags |
    | `migma tags create --name "VIP"` | Create a tag  |
    | `migma tags delete <id>`         | Delete a tag  |
  </Accordion>

  <Accordion title="Segments" icon="layer-group">
    | Command                                                                                                                                                                             | Description                                   |
    | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
    | `migma segments list`                                                                                                                                                               | List all segments                             |
    | `migma segments create --name "Active" --description "..."`                                                                                                                         | Create a segment                              |
    | `migma segments create --name "Campaign openers" --filters '{"activity":[{"action":"opened","channel":"email","mode":"within","unit":"days","amount":14,"campaignId":"cmp_123"}]}'` | Create an activity or campaign-scoped segment |
    | `migma segments get <id>`                                                                                                                                                           | Get segment details                           |
    | `migma segments delete <id>`                                                                                                                                                        | Delete a segment                              |
  </Accordion>
</AccordionGroup>

***

## Infrastructure

<AccordionGroup>
  <Accordion title="Projects" icon="building">
    | Command                       | Description                                |
    | ----------------------------- | ------------------------------------------ |
    | `migma projects list`         | List all projects (`--all` for every page) |
    | `migma projects get <id>`     | Get project details                        |
    | `migma projects import <url>` | Import brand from URL (`--wait` to block)  |
    | `migma projects use <id>`     | Set default project                        |
  </Accordion>

  <Accordion title="Domains" icon="globe">
    ```bash theme={null}
    # Instant managed domain (no DNS — see /sending-domains/overview)
    migma domains managed create mycompany

    # Custom domain
    migma domains add mail.yourbrand.com
    migma domains verify mail.yourbrand.com

    # Transactional stream (notify.yourbrand.com) to isolate reputation
    migma domains streams create yourbrand.com --stream transactional
    ```

    | Command                                                     | Description                                   |
    | ----------------------------------------------------------- | --------------------------------------------- |
    | `migma domains list`                                        | List sending domains                          |
    | `migma domains add <domain>`                                | Add a custom domain                           |
    | `migma domains verify <domain>`                             | Verify DNS records                            |
    | `migma domains managed create <prefix>`                     | Create instant subdomain                      |
    | `migma domains managed delete <domain>`                     | Delete managed subdomain                      |
    | `migma domains streams create <rootDomain> --stream <type>` | Provision a transactional or marketing stream |
  </Accordion>

  <Accordion title="Events & Webhooks" icon="bolt">
    | Command                                                  | Description       |
    | -------------------------------------------------------- | ----------------- |
    | `migma webhooks list`                                    | List all webhooks |
    | `migma webhooks create --url <url> --events <events...>` | Create a webhook  |
    | `migma webhooks test <id>`                               | Send a test event |
    | `migma webhooks delete <id>`                             | Delete a webhook  |
  </Accordion>
</AccordionGroup>

***

## Options

The root CLI accepts `--json`, and most project-scoped commands accept `--project <id>`:

| Flag             | Description                                             |
| ---------------- | ------------------------------------------------------- |
| `--json`         | Machine-readable JSON output                            |
| `--project <id>` | Override the default project on project-scoped commands |
| `--help`         | Show help for any command                               |

```bash theme={null}
# Pipe JSON into jq
migma contacts list --json | jq '.contacts[].email'
```

***

## Configuration

The CLI stores config in `~/.migma/config.json`:

| Setting        | Priority                                                    |
| -------------- | ----------------------------------------------------------- |
| **API key**    | `MIGMA_API_KEY` env var → config file                       |
| **Project ID** | `--project` flag → `MIGMA_PROJECT_ID` env var → config file |

***

## Common workflows

<Steps>
  <Step title="Generate → Validate → Send">
    ```bash theme={null}
    migma generate "Black Friday — 40% off everything" --wait
    migma validate all --conversation <conversationId>
    migma send --to test@yourbrand.com --from-conversation <conversationId> \
      --from hello@yourbrand.migma.email --from-name "Your Brand" \
      --subject "Black Friday Sale"
    migma send --segment seg_vip --email <emailId> \
      --from hello@yourbrand.migma.email --from-name "Your Brand" \
      --subject "Black Friday Sale"
    ```
  </Step>

  <Step title="Import → Generate → Export to Klaviyo">
    ```bash theme={null}
    migma projects import https://yourbrand.com --wait
    migma projects use <projectId>
    migma generate "Monthly newsletter" --wait
    migma export klaviyo <conversationId>
    ```
  </Step>

  <Step title="CSV import → Tag → Send">
    ```bash theme={null}
    migma contacts import ./subscribers.csv
    migma tags create --name "Launch List"
    migma send --tag <tagId> --email <emailId> \
      --from hello@yourbrand.migma.email --from-name "Your Brand" \
      --subject "We're live!"
    ```
  </Step>
</Steps>

***

<CardGroup cols={3}>
  <Card title="npm" icon="npm" href="https://www.npmjs.com/package/@migma/cli">
    View on npm
  </Card>

  <Card title="Node.js SDK" icon="code" href="/sdk">
    Use the SDK in your apps
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Full endpoint docs
  </Card>
</CardGroup>
