Skip to content
Merged
2 changes: 2 additions & 0 deletions cmd/nylas/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/nylas/cli/internal/cli/config"
"github.com/nylas/cli/internal/cli/contacts"
"github.com/nylas/cli/internal/cli/dashboard"
"github.com/nylas/cli/internal/cli/deliverability"
"github.com/nylas/cli/internal/cli/demo"
"github.com/nylas/cli/internal/cli/email"
"github.com/nylas/cli/internal/cli/mcp"
Expand Down Expand Up @@ -49,6 +50,7 @@ func main() {
rootCmd.AddCommand(calendar.NewCalendarCmd())
rootCmd.AddCommand(contacts.NewContactsCmd())
rootCmd.AddCommand(dashboard.NewDashboardCmd())
rootCmd.AddCommand(deliverability.NewDeliverabilityCmd())
rootCmd.AddCommand(oauthcmd.NewOAuthCmd())
// The dashboard commands renew OAuth-backed sessions through `nylas oauth`.
oauthcmd.WireDashboard()
Expand Down
1 change: 1 addition & 0 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ internal/
auth/ # Authentication
calendar/ # Calendar & events
contacts/ # Contact management
deliverability/ # Send/tracking events, metrics, send alerts
email/ # Email operations
integration/ # CLI integration tests
mcp/ # MCP server command
Expand Down
22 changes: 22 additions & 0 deletions docs/COMMANDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,28 @@ nylas workflow delete <workflow-id> --yes

---

## Deliverability

```bash
nylas deliverability send-events list [--event-type bounced] [--start 24h] # Send activity
nylas deliverability send-events show <event-id> # One send event
nylas deliverability send-events message <message-id> # Per-recipient timeline
nylas deliverability send-events summary [--start YYYY-MM-DD --end YYYY-MM-DD] # Health, totals, rates
nylas deliverability send-events timeseries [--granularity day|week|month]
nylas deliverability send-events breakdown [--group-by recipient_domain]
nylas deliverability tracking-events list|show|message|summary|timeseries|breakdown
nylas deliverability send-alerts list
nylas deliverability send-alerts create --metric bounce_rate --threshold 5 --window-hours 1
nylas deliverability send-alerts update <rule-id> --threshold 3
nylas deliverability send-alerts delete <rule-id> --yes
```

**Scope:** Agent Account and Transactional send messages only; connected-grant (Google, Microsoft) sends are not included. **Auth:** application-level (API key, no grant). **Time:** activity `--start/--end` take timestamps or look-backs (`24h`, `7d`); metrics take UTC dates `YYYY-MM-DD`.

**Details:** `docs/commands/deliverability.md`

---

## Folders & Threads

```bash
Expand Down
2 changes: 2 additions & 0 deletions docs/DEVELOPMENT.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ make test-integration

**CRITICAL:** Integration tests create real resources. Always use `make ci-full` for automatic cleanup.

`internal/cli/integration/deliverability_test.go` needs only `NYLAS_API_KEY` (no grant). It reads send and tracking activity and metrics, and creates, updates and deletes one send alert rule. It skips the rule test when the application already has 20 rules.

### OAuth authorization server tests

`internal/cli/integration/oauth_test.go` drives a real dashboard-account
Expand Down
2 changes: 2 additions & 0 deletions docs/INDEX.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ Quick navigation guide to find the right documentation for your needs.
- **TUI** → [commands/tui.md](commands/tui.md)
- **Workflows (OTP)** → [commands/workflows.md](commands/workflows.md)
- **Templates** → [commands/templates.md](commands/templates.md)
- **Deliverability (send/tracking events, send alerts)** → [commands/deliverability.md](commands/deliverability.md)

### AI & MCP

Expand Down Expand Up @@ -141,6 +142,7 @@ docs/
│ ├── audit.md # Audit logging & invoker tracking
│ ├── tui.md # Terminal UI
│ ├── templates.md # Email templates
│ ├── deliverability.md # Send/tracking events & send alerts
│ └── workflows.md # OTP & automation
│
├── ai/ # AI configuration (8 files)
Expand Down
115 changes: 115 additions & 0 deletions docs/commands/deliverability.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# Deliverability

Use `nylas deliverability` to see what happened to the email your application sends. The commands follow the "Deliverability & Engagement" section of the Nylas API reference:

| Command group | Data | API routes |
|---|---|---|
| `send-events` | Send activity and send metrics | `/v3/activity/send`, `/v3/metrics/send` |
| `tracking-events` | Opens, link clicks and engagement metrics | `/v3/activity/tracking`, `/v3/metrics/tracking` |
| `send-alerts` | Alert rules on send rates | `/v3/alerts/send` |

**These commands cover Agent Account and Transactional send messages only.** Messages sent from a connected grant, such as a Google or Microsoft account, aren't included. Tracking events exist only for messages sent with open or link tracking turned on. See [Monitor delivery and engagement](https://developer.nylas.com/docs/v3/agent-accounts/monitor-delivery-engagement/) in the API docs.

All of these routes are application-level. They use your API key (`nylas auth config` or `NYLAS_API_KEY`) and do not take a grant. A grant access token gets `403 api.forbidden`.

---

## Time windows

The two kinds of command take different time formats:

| Commands | `--start` / `--end` | Default | Limit |
|---|---|---|---|
| `list` (activity) | Unix seconds, `YYYY-MM-DD`, `"YYYY-MM-DD HH:MM[:SS]"` or `YYYY-MM-DDTHH:MM[:SS]` (UTC), RFC3339, or a look-back such as `24h`, `7d`, `2w` | `--end` = now, `--start` = UTC midnight 6 days before `--end` | 90 days. An older `--start` is moved to 90 days ago; an older `--end` is rejected. |
| `summary`, `timeseries`, `breakdown` (metrics) | UTC date, `YYYY-MM-DD`, both days included | `--end` = today, `--start` = 6 days before `--end` | 365 days |

A look-back value counts back from now. For example, `--start 24h` means "24 hours ago". On `list`, a time without a zone is UTC, and a bare date is a whole UTC day: `--start 2026-10-01` starts at 00:00:00Z and `--end 2026-10-01` ends at 23:59:59Z. Words such as `today` or `9am` are not accepted, because they mean a different time on each run.

Unlike most `nylas` commands, which show local time, deliverability commands print UTC, for example `2026-10-29 16:13:55 UTC`. This matches the API and the UTC days used by metrics, and you can paste a printed time straight into `--start` or `--end`.

---

## Send events

```bash
# Activity feed, newest first
nylas deliverability send-events list
nylas deliverability send-events list --event-type bounced --event-type complaint --start 7d
nylas deliverability send-events list --recipient-domain gmail.com --bounce-class hard
nylas deliverability send-events list --message-id "<abc@mail.example.com>" --json

# One event, with the SMTP / bounce / complaint detail
nylas deliverability send-events show <event-id>

# Every recipient's timeline for one message
nylas deliverability send-events message <message-id>

# Metrics
nylas deliverability send-events summary
nylas deliverability send-events summary --start 2026-10-01 --end 2026-10-31 --sending-domain mail.example.com
nylas deliverability send-events timeseries --granularity week --start 2026-08-01
nylas deliverability send-events breakdown --group-by recipient_domain --sort bounce_rate:desc
```

**`list` filters:** `--event-type` (repeatable: `accepted`, `delivered`, `bounced`, `complaint`, `rejected`), `--bounce-class` (`hard`, `soft`, `undetermined`), `--sending-domain`, `--from`, `--grant-id`, `--recipient`, `--recipient-domain`, `--message-id`, `--thread-id`, `--order asc|desc`.

**Paging:** `list` shows one page (`--limit`, default 50, max 200). When there are more rows it prints `Next page token: …`. Pass that token with `--page-token`. Keep the other flags the same, because the token belongs to that exact query, including `--start` and `--end`. A look-back such as `7d` gives a different time on every run, so it cannot be used with `--page-token`. When page 1 used a look-back, the CLI prints `Next page: --page-token … --start <epoch>` instead, with `--end <epoch>` too if you set `--end`. Run the next page with exactly those flags. (Without `--end`, the token itself keeps the end time.) `--quiet` prints only IDs and never a page token. To page from a script, use `--json` and read `next_cursor` from the body. After a look-back, `--json` and `--format yaml` also write the `Next page:` line to stderr, because the body does not show the resolved window.

**`summary`:** health is always graded on the **last 7 days**, whatever window you ask for. The states are `healthy`, `at_risk`, `critical` and `insufficient_data` (fewer than 100 sends). Totals and rate tiles use your window and compare it with the period of the same length just before it. When the state is `at_risk` or `critical`, `summary` also lists up to 3 findings.

**`timeseries`:** `--granularity auto|day|week|month`. `auto` uses days up to 21 days, weeks up to 92 days, and months after that.

**`breakdown`:** `--group-by sending_domain|agent_account|recipient_domain`, `--sort <key>:<asc|desc>` (keys: `key`, `sent`, `delivery_rate`, `bounce_rate`, `complaint_rate`), `--limit` 1–100 (default 25). Rows after the limit are added together into one `(others)` row. A `recipient_domain` breakdown only covers the last 90 days.

**Rates:** a rate shows `—` when its denominator is 0. That means "no data", not 0%. The bounce rate counts hard bounces only.

---

## Tracking events

```bash
nylas deliverability tracking-events list --event-type link_clicked --start 7d
nylas deliverability tracking-events list --label welcome-campaign --json
nylas deliverability tracking-events show <event-id>
nylas deliverability tracking-events message <message-id>

nylas deliverability tracking-events summary --start 2026-10-01
nylas deliverability tracking-events timeseries --granularity day
nylas deliverability tracking-events breakdown --group-by agent_account --sort open_rate:desc
```

**`list` filters:** `--event-type` (repeatable: `opened`, `link_clicked`), `--sending-domain`, `--from`, `--grant-id`, `--message-id`, `--thread-id`, `--label`.

**`message`:** shows open and click totals, clicks per link, and the newest 100 interactions. The totals count every interaction, not only the 100 shown.

**Rates:** open rate = first opens ÷ messages sent with open tracking. Click rate = first clicks ÷ messages sent with link tracking. `breakdown` sort keys: `key`, `tracked_opens`, `tracked_links`, `open_rate`, `click_rate`.

---

## Send alerts

A send alert rule watches one send rate for each sending domain. When the rate crosses the threshold, Nylas sends the `alert.triggered` webhook to your application's webhook subscriptions. An application can have at most 20 rules.

```bash
nylas deliverability send-alerts list
nylas deliverability send-alerts create --metric bounce_rate --threshold 5 --window-hours 1 --min-volume 50
nylas deliverability send-alerts create --metric delivery_rate --threshold 95 --window-hours 24
nylas deliverability send-alerts show <rule-id>
nylas deliverability send-alerts update <rule-id> --threshold 3
nylas deliverability send-alerts delete <rule-id> --yes
```

| Flag | Meaning |
|---|---|
| `--metric` | `bounce_rate`, `complaint_rate` or `delivery_rate` |
| `--threshold` | Percentage with at most 2 decimals. `bounce_rate` and `complaint_rate` fire **above** it (0 to <100). `delivery_rate` fires **below** it (>0 to 100). |
| `--window-hours` | Look-back window, 1–24 hours |
| `--min-volume` | Sends needed in the window before the rule can fire (default 0) |

`create` needs `--metric`, `--threshold` and `--window-hours`. `update` sends only the flags you give and keeps every other field.

---

## Output

All commands support `--json`, `--format yaml` and `--quiet`. For `list`, the JSON output is the full API response (`data`, `next_cursor`, `request_id`), so a script can page through results. `--quiet` prints one ID per line.
121 changes: 121 additions & 0 deletions internal/adapters/nylas/deliverability_activity.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package nylas

import (
"context"
"net/url"

"github.com/nylas/cli/internal/domain"
)

// ListSendEvents returns one page of GET /v3/activity/send.
func (c *HTTPClient) ListSendEvents(ctx context.Context, params *domain.SendEventListParams) (*domain.SendEventListResponse, error) {
if params == nil {
params = &domain.SendEventListParams{}
}
// event_type repeats as separate keys; the API rejects a comma-joined value.
queryURL := activityWindowQuery(params.Start, params.End, params.Order, params.Limit, params.PageToken).
AddSlice("event_type", params.EventTypes).
Add("bounce_class", params.BounceClass).
Add("sending_domain", params.SendingDomain).
Add("from", params.From).
Add("grant_id", params.GrantID).
Add("recipient", params.Recipient).
Add("recipient_domain", params.RecipientDomain).
Add("message_id", params.MessageID).
Add("thread_id", params.ThreadID).
BuildURL(c.baseURL + "/v3/activity/send")

var result domain.SendEventListResponse
if err := c.doGet(ctx, queryURL, &result); err != nil {
return nil, err
}
return &result, nil
}

// GetSendEvent returns one send event by its 64-hex ID.
func (c *HTTPClient) GetSendEvent(ctx context.Context, eventID string) (*domain.SendEvent, error) {
if err := validateRequired("event ID", eventID); err != nil {
return nil, err
}
var result struct {
Data domain.SendEvent `json:"data"`
}
if err := c.doGet(ctx, c.baseURL+"/v3/activity/send/"+url.PathEscape(eventID), &result); err != nil {
return nil, err
}
return &result.Data, nil
}

// GetSendMessageActivity returns every recipient's send timeline for one message.
func (c *HTTPClient) GetSendMessageActivity(ctx context.Context, messageID string) (*domain.SendMessageActivity, error) {
if err := validateRequired("message ID", messageID); err != nil {
return nil, err
}
var result struct {
Data domain.SendMessageActivity `json:"data"`
}
if err := c.doGet(ctx, c.baseURL+"/v3/activity/send/messages/"+url.PathEscape(messageID), &result); err != nil {
return nil, err
}
return &result.Data, nil
}

// ListTrackingEvents returns one page of GET /v3/activity/tracking.
func (c *HTTPClient) ListTrackingEvents(ctx context.Context, params *domain.TrackingEventListParams) (*domain.TrackingEventListResponse, error) {
if params == nil {
params = &domain.TrackingEventListParams{}
}
queryURL := activityWindowQuery(params.Start, params.End, params.Order, params.Limit, params.PageToken).
AddSlice("event_type", params.EventTypes).
Add("sending_domain", params.SendingDomain).
Add("from", params.From).
Add("grant_id", params.GrantID).
Add("message_id", params.MessageID).
Add("thread_id", params.ThreadID).
Add("label", params.Label).
BuildURL(c.baseURL + "/v3/activity/tracking")

var result domain.TrackingEventListResponse
if err := c.doGet(ctx, queryURL, &result); err != nil {
return nil, err
}
return &result, nil
}

// GetTrackingEvent returns one tracking event by its 64-hex ID.
func (c *HTTPClient) GetTrackingEvent(ctx context.Context, eventID string) (*domain.TrackingEvent, error) {
if err := validateRequired("event ID", eventID); err != nil {
return nil, err
}
var result struct {
Data domain.TrackingEvent `json:"data"`
}
if err := c.doGet(ctx, c.baseURL+"/v3/activity/tracking/"+url.PathEscape(eventID), &result); err != nil {
return nil, err
}
return &result.Data, nil
}

// GetTrackingMessageActivity returns open and click totals and recent interactions for one message.
func (c *HTTPClient) GetTrackingMessageActivity(ctx context.Context, messageID string) (*domain.TrackingMessageActivity, error) {
if err := validateRequired("message ID", messageID); err != nil {
return nil, err
}
var result struct {
Data domain.TrackingMessageActivity `json:"data"`
}
if err := c.doGet(ctx, c.baseURL+"/v3/activity/tracking/messages/"+url.PathEscape(messageID), &result); err != nil {
return nil, err
}
return &result.Data, nil
}

// activityWindowQuery adds the window and paging params shared by both feeds; zero means server default.
func activityWindowQuery(start, end int64, order string, limit int, pageToken string) *QueryBuilder {
return NewQueryBuilder().
AddInt64("start", start).
AddInt64("end", end).
Add("order", order).
AddInt("limit", limit).
Add("page_token", pageToken)
}
79 changes: 79 additions & 0 deletions internal/adapters/nylas/deliverability_alerts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package nylas

import (
"context"
"net/http"
"net/url"

"github.com/nylas/cli/internal/domain"
)

// ListSendAlertRules returns every send alert rule for the application (at most 20, unpaginated).
func (c *HTTPClient) ListSendAlertRules(ctx context.Context) ([]domain.SendAlertRule, error) {
var result struct {
Data []domain.SendAlertRule `json:"data"`
}
if err := c.doGet(ctx, c.baseURL+"/v3/alerts/send", &result); err != nil {
return nil, err
}
return result.Data, nil
}

// GetSendAlertRule returns one send alert rule.
func (c *HTTPClient) GetSendAlertRule(ctx context.Context, ruleID string) (*domain.SendAlertRule, error) {
if err := validateRequired("rule ID", ruleID); err != nil {
return nil, err
}
var result struct {
Data domain.SendAlertRule `json:"data"`
}
if err := c.doGet(ctx, sendAlertRuleURL(c.baseURL, ruleID), &result); err != nil {
return nil, err
}
return &result.Data, nil
}

// CreateSendAlertRule creates a send alert rule. It does not retry, so a timeout cannot create a duplicate.
func (c *HTTPClient) CreateSendAlertRule(ctx context.Context, req *domain.SendAlertRuleRequest) (*domain.SendAlertRule, error) {
resp, err := c.doJSONRequestNoRetry(ctx, http.MethodPost, c.baseURL+"/v3/alerts/send", req, http.StatusCreated)
if err != nil {
return nil, err
}
var result struct {
Data domain.SendAlertRule `json:"data"`
}
if err := c.decodeJSONResponse(resp, &result); err != nil {
return nil, err
}
return &result.Data, nil
}

// UpdateSendAlertRule changes only the fields set in req (PUT with partial semantics).
func (c *HTTPClient) UpdateSendAlertRule(ctx context.Context, ruleID string, req *domain.SendAlertRuleRequest) (*domain.SendAlertRule, error) {
if err := validateRequired("rule ID", ruleID); err != nil {
return nil, err
}
resp, err := c.doJSONRequest(ctx, http.MethodPut, sendAlertRuleURL(c.baseURL, ruleID), req, http.StatusOK)
if err != nil {
return nil, err
}
var result struct {
Data domain.SendAlertRule `json:"data"`
}
if err := c.decodeJSONResponse(resp, &result); err != nil {
return nil, err
}
return &result.Data, nil
}

// DeleteSendAlertRule deletes a send alert rule.
func (c *HTTPClient) DeleteSendAlertRule(ctx context.Context, ruleID string) error {
if err := validateRequired("rule ID", ruleID); err != nil {
return err
}
return c.doDelete(ctx, sendAlertRuleURL(c.baseURL, ruleID))
}

func sendAlertRuleURL(baseURL, ruleID string) string {
return baseURL + "/v3/alerts/send/" + url.PathEscape(ruleID)
}
Loading
Loading