# Automations

Create and manage event-driven transactional automations with a Bearer `gm_…` API key (or dashboard session).

Base URL: `https://api.groundmail.dev`

You can also build flows visually in the dashboard canvas under **Automations**.

---

## Authentication

```http
Authorization: Bearer gm_…
```

---

## Create an automation

`POST /automations`

Creates a **draft**. Activate it before events will match. Each email step sends a published [template](https://docs.groundmail.dev/templates) by its id or alias and fills the template's fields from the event (see [The email a step sends](#the-email-a-step-sends)).

```json
{
  "name": "Welcome email",
  "trigger": {
    "type": "event",
    "event": "user.created"
  },
  "steps": [
    {
      "type": "send_email",
      "email": {
        "from": "you@yourdomain.com",
        "to": "{{event.email}}",
        "template": {
          "id": "welcome",
          "variables": {
            "name": "{{event.data.name}}"
          }
        }
      }
    }
  ]
}
```

Examples below are generated from `src/lib/dx/snippets.ts` (same source as the dashboard).

### curl

```bash
curl -X POST https://api.groundmail.dev/automations \
  -H "Authorization: Bearer gm_…" \
  -H "Content-Type: application/json" \
  -d '{"name":"Welcome email","trigger":{"type":"event","event":"user.created"},"steps":[{"type":"send_email","email":{"from":"you@yourdomain.com","to":"{{event.email}}","template":{"id":"welcome","variables":{"name":"{{event.data.name}}"}}}}]}'
```

### npm

```ts
npm install groundmail

import { Groundmail } from 'groundmail'

const client = new Groundmail('gm_…')

const { automation } = await client.automations.create({
  name: 'Welcome email',
  trigger: { type: 'event', event: 'user.created' },
  steps: [
    {
      type: 'send_email',
      email: {
        from: 'you@yourdomain.com',
        to: '{{event.email}}',
        template: { id: 'welcome', variables: { name: '{{event.data.name}}' } },
      },
    },
  ],
})

await client.automations.activate(automation.id)
```

### CLI

```bash
GROUNDMAIL_API_KEY=gm_… npx -y --package=groundmail-cli -- groundmail automations create --file ./welcome.json
GROUNDMAIL_API_KEY=gm_… npx -y --package=groundmail-cli -- groundmail automations activate --id "$AUTOMATION_ID"
```

`welcome.json` should match the request body above.

### Folders

Add `"folder": "Onboarding"` on create or update to file the automation in a dashboard folder. The folder is matched by name (any case) and created if it doesn't exist. Send `"folder": null` (or `""`) on update to take it out of any folder. Every automation in a response has `folder`: the folder's name, or `null`. Folders only organize the list; they don't change how an automation runs.

From the CLI, pass `--folder Onboarding` to `automations create` or `automations update`, or put `"folder"` in the `--file` JSON.

---

## Endpoints

| Method | Path | Notes |
|--------|------|-------|
| `GET` | `/automations` | List |
| `POST` | `/automations` | Create draft |
| `GET` | `/automations/{id}` | Get |
| `PATCH` | `/automations/{id}` | Update name/trigger/steps/folder |
| `DELETE` | `/automations/{id}` | Delete |
| `POST` | `/automations/{id}` | `{ "action": "activate" \| "pause" }` |
| `GET` | `/automations/runs` | Optional `?automation_id=` and `?test=` (`true` for runs started with a test key, `false` for live runs). Each run has a `test` field |
| `GET` | `/automations/runs/{id}` | Run detail |
| `POST` | `/automations/runs/{id}` | `{ "action": "cancel" \| "retry" }` |

---

## Step types

| Type | Purpose |
|------|---------|
| `send_email` | Send a published [template](https://docs.groundmail.dev/templates) (`email.template`) through the same send path as `POST /emails`. See [The email a step sends](#the-email-a-step-sends) |
| `send_sms` | Send SMS via [Twilio](https://docs.groundmail.dev/integrations) — requires a connected integration and `sms.to` + `sms.body` |
| `delay` | Wait `seconds` before the next step |
| `condition` | "Only if": continue only if true; **false stops the run** |
| `wait_for_event` | Pause until another event arrives (optional `timeout_seconds`; `on_timeout` `continue` or `fail`, default `fail`) |
| `branch` | If / otherwise: one question, two paths (`then` and `else`), each running to its own end. See [If / otherwise](#if--otherwise) |

**Trigger options:**

- `cancel_on_events` — array of event names that cancel active runs for the same recipient when fired.
- `once_per_contact` — `true` enrols each recipient at most once, ever. Matched on the trigger event's `email` or `user_id`. Use it when the trigger event can fire more than once for the same person (a retried signup, a per-item milestone).
- `cooldown_days` — do not enrol the same recipient again within this many days (1–3650) of their last run on this automation.

A matching event that is not enrolled because of these options is reported in the event response as `enrollment_skips`. Dashboard test runs never count as an enrolment.

Placeholders in email and SMS steps: `{{event.email}}`, `{{event.user_id}}`, `{{event.data.foo}}`. Add a fallback for empty values with `{{event.data.name | default:"there"}}`. Values merged into HTML are HTML-escaped.

### The email a step sends

Every automation email is a template. A `send_email` step names a **published** template by id or alias and fills its fields:

```json
{
  "type": "send_email",
  "email": {
    "sender": "billing",
    "to": "{{event.email}}",
    "template": {
      "id": "payment-failed",
      "variables": {
        "name": "{{event.data.customer.name | default:\"there\"}}",
        "amount": "{{event.data.invoice.amount}}"
      }
    }
  }
}
```

- **`template.id`**: the template's id or alias. The step always sends the template's live (published) version, so publishing a new version changes every automation that sends it, and every send from your code. A step whose template is a draft fails at send time; the dashboard warns about it.
- **`template.variables`**: a value for each of the template's fields (`{{name}}` in the template). Values are resolved against the run when the step sends, so `{{event.data.…}}` works here.
- **The run, directly**: a template sent by an automation can also read the run itself: `{{event.data.plan}}`, `{{event.email}}`, `{{contact.email}}` and `{{contact.user_id}}` (the person the run is for) and `{{automation.name}}`. Fields the step sets in `variables` win.
- **Per-step overrides**: `subject` (this step's subject instead of the template's), `from` or `sender`, `reply_to`, `tags` and `headers` (`category` is deprecated and ignored). The body is always the template's; `html` and `text` can't be combined with `template`.

In the dashboard, "Edit email" on a step edits its template in place (with a warning that publishing changes every automation using it) or makes a copy for that automation. Deleting a template an automation still sends returns `409 conflict` naming the automations and steps; point those steps at another template first.

#### Inline emails (written from code)

A step may still carry its own `subject` plus `html` and/or `text` instead of `template`. This shape stays supported for flows managed entirely from code: the step sends exactly what it carries, merged with the run's placeholders. The dashboard shows such a step as written from code and offers **Turn into template**, which makes a published template of it and points the step at it.

```json
{
  "type": "send_email",
  "email": {
    "from": "you@yourdomain.com",
    "to": "{{event.email}}",
    "subject": "Welcome",
    "html": "<p>Hi {{event.data.name | default:\"there\"}}</p>"
  }
}
```

### If / otherwise

A `branch` step asks one question and sends each person down one of two paths. The common case is a nudge: wait a few days, then check whether they did the thing.

```json
{
  "name": "First project nudge",
  "trigger": { "event": "user.created" },
  "steps": [
    { "type": "delay", "seconds": 259200 },
    {
      "type": "branch",
      "if": { "event": "project.created" },
      "then": [],
      "else": [
        {
          "type": "send_email",
          "email": {
            "from": "hello@yourdomain.com",
            "to": "{{event.email}}",
            "template": { "id": "need-a-hand" }
          }
        }
      ]
    }
  ]
}
```

`if` is one of:

- `{ "event": "project.created" }`: has this person sent that event (`POST /events`, matched on `user_id`, else `email`) since this run started? Events sent with a test key only count for test runs.
- `{ "path": "event.data.plan", "operator": "equals", "value": "pro" }`: a value on the event that started the run, with the same operators as `condition`.

Rules:

- The `branch` step is always the last step in `steps`. Anything that should happen after it goes inside a path; if both paths need the same email, add it to each.
- Paths cannot contain another `branch`.
- An empty path is fine: people who take it finish there. At least one path needs a step.
- The 20-step limit counts every step in every path.

Run steps report where they sit with `step_path` (`"1"`, `"1.then.0"`, `"1.else.0"`), as do `automation.step_completed` webhooks. A `branch` step's `output` says which path the person took: `{ "matched": false, "path_taken": "else", "event": "project.created", ... }`. `step_index` numbers the steps laid out flat: the top level, then the `then` path, then the `else` path, which is also how the dashboard numbers them.

### Who an email step is from

A `send_email` step sets `email.from`, or `email.sender` with a saved [sender](https://docs.groundmail.dev/senders)'s handle:

```json
{ "type": "send_email", "email": { "sender": "billing", "to": "{{event.email}}", "template": { "id": "receipt" } } }
```

The sender is looked up each time the step sends, so editing it (name, address, reply-to) changes every step that uses it. In the dashboard, the From on an email step is a picker of your senders. New automations start with your default sender. A step with a literal `from` keeps sending from that address. A sender an automation uses can't be deleted until the automation picks another.

### Email category and unsubscribe

Groundmail decides whether each email a step sends is transactional or product ([how](https://docs.groundmail.dev/deliverability#detected-category)). A step's `email.category` is deprecated: `transactional` and `product` are accepted and ignored, and `newsletter` is rejected (approved accounts send newsletters through [`POST /emails`](https://docs.groundmail.dev/emails)). `product` mail honours recipient opt-outs, carries a `List-Unsubscribe` header and is sent from the product IPs ([streams](https://docs.groundmail.dev/deliverability#transactional-and-product-streams)); put `{{unsubscribe_url}}` in the body to give the reader a visible link (it is replaced, never appended). Creating or updating an automation returns `warnings` when a `product` step has no such link.

If a recipient opted out of the category the email goes out as, the step is skipped and the run completes instead of failing.

### Pausing and long delays

Pausing an automation holds its in-flight runs where they are, including runs sitting in a delay; nothing sends until it is activated again. A run whose scheduled step is overdue is picked back up automatically; one more than 7 days overdue is cancelled with the reason on the run rather than sent late.

### SMS example (`send_sms`)

Connect Twilio first ([`integrations twilio connect`](https://docs.groundmail.dev/integrations)), then create an automation:

```json
{
  "name": "Auth OTP (SMS)",
  "trigger": { "type": "event", "event": "auth.code_requested" },
  "steps": [
    {
      "type": "send_sms",
      "sms": {
        "to": "{{event.data.phone}}",
        "body": "Your code is {{event.data.code}}. Expires in 10 min."
      }
    }
  ]
}
```

```bash
GROUNDMAIL_API_KEY=gm_… npx -y --package=groundmail-cli -- groundmail integrations twilio connect \
  --account-sid AC… --auth-token … --from +15551234567
GROUNDMAIL_API_KEY=gm_… npx -y --package=groundmail-cli -- groundmail automations create --file ./otp-sms.json
GROUNDMAIL_API_KEY=gm_… npx -y --package=groundmail-cli -- groundmail automations activate --id "$AUTOMATION_ID"
```

---

## Trigger the flow

After activate, send events with [`POST /events`](https://docs.groundmail.dev/events) or:

```bash
groundmail events send --name user.created --email user@example.com --data '{"name":"Ada"}'
```
