Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,9 @@ mailtrap company-info create --domain-id 123 --name "Your Company" --address "12
--city "San Francisco" --country US --zip-code 94105 --website-url "https://yourdomain.com"
mailtrap company-info update --domain-id 123 --city "New York" --zip-code 10001

# Suppressions
# Suppressions (--include-topic-unsubscriptions needs a token that can read contacts; without it, topic rows are left out silently)
mailtrap suppressions list --email "bounced@example.com"
mailtrap suppressions list --include-topic-unsubscriptions
Comment thread
Rabsztok marked this conversation as resolved.
Resolved
mailtrap suppressions create --email "bounced@example.com" --domain-id 123 --sending-stream transactional
mailtrap suppressions delete --id "2fe148b8-b019-431f-ab3f-107663fdf868"

Expand Down Expand Up @@ -162,6 +163,8 @@ mailtrap tokens reset --id 42 --expires-at never

# Contacts
mailtrap contacts create --email "user@example.com" --first-name "John"
mailtrap contacts update --id <CONTACT_ID> --email "user@example.com" \
--subscription-topics '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]'
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
mailtrap contact-lists list
mailtrap contact-lists list --search news
mailtrap contact-fields create --name "Company" --data-type text --merge-tag "{{company}}"
Expand All @@ -171,9 +174,14 @@ mailtrap email-campaigns list --search spring
mailtrap email-campaigns create --name "Spring Sale" --domain-id 4321 --from-local-part news --subject "Spring is here"
mailtrap email-campaigns update --id 4567 --body-html '<h1>Hi {{first_name}}!</h1><a href="__unsubscribe_url__">Unsubscribe</a>' --contact-list-ids 55,56
mailtrap email-campaigns update --id 4567 --clear-contact-lists
mailtrap email-campaigns update --id 4567 --subscription-topic-id 7
mailtrap email-campaigns schedule --id 4567 --datetime "2030-01-01T09:00:00Z"
mailtrap email-campaigns stats --id 4567 --start-date 2026-05-01 --end-date 2026-05-31

# Subscription topics
mailtrap subscription-topics list
mailtrap subscription-topics get --id 7

# Sandboxes & projects
mailtrap projects list
mailtrap sandboxes list
Expand All @@ -195,7 +203,7 @@ mailtrap domains list --output text
export MAILTRAP_OUTPUT=json
```

With `--output json`, commands print the API response as returned. Paginated lists (`inbound messages list`, `inbound threads list`, `email-logs list`, `email-campaigns list`, `templates list`, `tracking-opt-outs list`) print the full response object, so the next-page cursor and, where the API provides one, the total count are available to scripts:
With `--output json`, commands print the API response as returned. Paginated lists (`inbound messages list`, `inbound threads list`, `email-logs list`, `email-campaigns list`, `subscription-topics list`, `templates list`, `tracking-opt-outs list`) print the full response object, so the next-page cursor and, where the API provides one, the total count are available to scripts:

```bash
mailtrap inbound messages list --inbox-id 735 -o json | jq -r '.last_id // empty'
Expand All @@ -220,6 +228,7 @@ mailtrap inbound messages list --inbox-id 735 -o json | jq -r '.last_id // empty
| **Contact Lists** | `contact-lists list`, `contact-lists get`, `contact-lists create`, `contact-lists update`, `contact-lists delete` |
| **Contact Fields** | `contact-fields list`, `contact-fields get`, `contact-fields create`, `contact-fields update`, `contact-fields delete` |
| **Email Campaigns** | `email-campaigns list`, `email-campaigns get`, `email-campaigns create`, `email-campaigns update`, `email-campaigns delete`, `email-campaigns start`, `email-campaigns schedule`, `email-campaigns cancel`, `email-campaigns terminate`, `email-campaigns reset`, `email-campaigns stats` |
| **Subscription Topics** | `subscription-topics list`, `subscription-topics get` |
| **Projects** | `projects list`, `projects get`, `projects create`, `projects update`, `projects delete` |
| **Sandboxes** | `sandboxes list`, `sandboxes get`, `sandboxes create`, `sandboxes update`, `sandboxes delete`, `sandboxes clean`, `sandboxes mark-read`, `sandboxes reset-credentials`, `sandboxes toggle-email`, `sandboxes reset-email` |
| **Messages** | `messages list`, `messages get`, `messages update`, `messages delete`, `messages forward`, `messages spam-score`, `messages html-analysis`, `messages headers`, `messages html`, `messages text`, `messages source`, `messages raw`, `messages eml` |
Expand Down
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/mailtrap/mailtrap-cli/internal/commands/sandboxes"
"github.com/mailtrap/mailtrap-cli/internal/commands/send"
"github.com/mailtrap/mailtrap-cli/internal/commands/stats"
"github.com/mailtrap/mailtrap-cli/internal/commands/subscriptiontopics"
"github.com/mailtrap/mailtrap-cli/internal/commands/suppressions"
"github.com/mailtrap/mailtrap-cli/internal/commands/templates"
"github.com/mailtrap/mailtrap-cli/internal/commands/tokens"
Expand Down Expand Up @@ -80,6 +81,7 @@ func NewRootCmd(f *cmdutil.Factory) *cobra.Command {
cmd.AddCommand(contact_lists.NewCmdContactLists(f))
cmd.AddCommand(contact_fields.NewCmdContactFields(f))
cmd.AddCommand(emailcampaigns.NewCmdEmailCampaigns(f))
cmd.AddCommand(subscriptiontopics.NewCmdSubscriptionTopics(f))

// Account Management
cmd.AddCommand(accounts.NewCmdAccounts(f))
Expand Down
33 changes: 31 additions & 2 deletions docs/TEST_PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ These were discovered during integration testing and are important for correct i
| `GET /contacts` | 404 (HTML page) | Endpoint may not exist or requires different path |
| `GET /suppressions` | `[...]` | Flat array |
| `GET /templates` | `{"data": [...], "pagination": {...}}` | Page-token pagination, no total |
| `GET /api/subscription_topics` | `{"data": [...], "pagination": {...}}` | Token-scoped (no account ID); page-token pagination, no total; `403` with an empty body on accounts without subscription topics |
| `GET /contacts/lists` | `[...]` | Flat array |
| `GET /contacts/fields` | `[...]` | Flat array |
| `GET /account_accesses` | `[...]` | Flat array |
Expand Down Expand Up @@ -198,7 +199,7 @@ Tests are organized by endpoint group. Each test specifies:
|---|------|---------|----------|
| 10.1 | Create contact | `mailtrap contacts create --email "test@integration.com"` | New contact in output |
| 10.2 | Get contact | `mailtrap contacts get --id <CONTACT_ID>` | Single contact details |
| 10.3 | Update contact | `mailtrap contacts update --id <CONTACT_ID> --first-name "Test"` | Updated contact |
| 10.3 | Update contact | `mailtrap contacts update --id <CONTACT_ID> --email "test@integration.com" --first-name "Test"` | Updated contact |
| 10.4 | List contacts | `mailtrap contacts list` | Table with contacts (may 404 — investigate) |
| 10.5 | Import contacts | `mailtrap contacts import --file contacts.csv` | Import initiated |
| 10.6 | Import status | `mailtrap contacts import-status --id <IMPORT_ID>` | Status details |
Expand Down Expand Up @@ -379,6 +380,32 @@ Prerequisite: Send an email with an attachment to the sandbox.

**Cleanup:** Delete created forward rules, inbox and folder (`inbound forward-rules delete`, `inbound inboxes delete`, `inbound folders delete`).

## 23. Subscription Topics

**Note:** `subscription-topics` commands take no `--account-id` (requests go to `/api/subscription_topics`). Run 23.1–23.12 on an account with subscription topics, two domains, a topic for every domain and a topic for one domain, and 23.13–23.17 on an account without them. Topics are created in the Mailtrap app.

| # | Test | Command | Expected |
|---|------|---------|----------|
| 23.1 | List topics | `mailtrap subscription-topics list` | Table with ID, NAME, DESCRIPTION, DOMAIN ID, CREATED AT; DOMAIN ID empty for the every-domain topic |
| 23.2 | List topics (JSON) | `mailtrap subscription-topics list --output json` | Valid JSON object with `data` and `pagination` |
| 23.3 | Next page keeps page size | `mailtrap subscription-topics list --per-page 1`, then run the `Next page:` hint | Hint is `--token 2 --per-page 1`; it prints the other topic |
| 23.4 | Get topic | `mailtrap subscription-topics get --id <TOPIC_ID>` | Single topic with an empty DELETED AT |
| 23.5 | Get deleted topic | Delete a topic in the app, then `mailtrap subscription-topics get --id <DELETED_TOPIC_ID>` | Topic with DELETED AT set; it is gone from 23.1 |
| 23.6 | Get missing ID | `mailtrap subscription-topics get` | Error: `required flag(s) "id" not set` |
| 23.7 | Campaign with topic | `mailtrap email-campaigns create --name "topic-test" --domain-id <DOMAIN_ID> --from-local-part news --subject "Hi" --subscription-topic-id <TOPIC_ID>` | TOPIC ID column shows the topic; `email-campaigns get --id <NEW_ID> -o json` has `subscription_topic_id` |
| 23.8 | Campaign with uncovered topic | `mailtrap email-campaigns update --id <NEW_ID> --subscription-topic-id <OTHER_DOMAIN_TOPIC_ID>` | `API error 422`, campaign unchanged |
| 23.9 | Contact topic preferences | `mailtrap contacts update --id <CONTACT_ID> --email <EMAIL> --subscription-topics '[{"subscription_topic_id":<TOPIC_ID>,"domain_id":<DOMAIN_ID>,"status":"unsubscribed"}]' -o json` | `subscription_topics` lists the topic as `unsubscribed` on that domain and `subscribed` on the other |
| 23.10 | Invalid topic entry | `mailtrap contacts update --id <CONTACT_ID> --email <EMAIL> --subscription-topics '[{"subscription_topic_id":<TOPIC_ID>,"status":"unsubscribed"}]'` | Error: `entry 1: domain_id must be greater than 0`; no request sent |
| 23.11 | Import with topics | `mailtrap contacts import --file contacts.json` with a contact carrying `subscription_topics` | Import completes; `contacts get` shows the preference |
| 23.12 | Topic unsubscriptions | `mailtrap suppressions list --include-topic-unsubscriptions` after 23.9 | A `topic unsubscription` row with TOPIC_ID and DOMAIN_NAME; without the flag, or with a token limited to one domain, the row is absent |
| 23.13 | Topics off: list | `mailtrap subscription-topics list` | `API error 403` |
| 23.14 | Topics off: campaign | `mailtrap email-campaigns create ... --subscription-topic-id 1` | Campaign saved; TOPIC ID empty |
| 23.15 | Topics off: contact read | `mailtrap contacts get --id <CONTACT_ID> -o json` | No `subscription_topics` key, no error |
| 23.16 | Topics off: contact write | `mailtrap contacts update --id <CONTACT_ID> --email <EMAIL> --subscription-topics '[{"subscription_topic_id":1,"domain_id":<DOMAIN_ID>,"status":"subscribed"}]'` | `API error 422` naming `subscription_topics` ("are not available for this account") |
| 23.17 | Topics off: suppressions | `mailtrap suppressions list --include-topic-unsubscriptions` | No `topic unsubscription` rows |

**Cleanup:** Delete the campaign created in 23.7 and the contacts imported in 23.11.

---

## Discovered Bugs / Issues
Expand Down Expand Up @@ -421,6 +448,7 @@ Run tests in dependency order so earlier tests create resources needed by later
20. **Organizations** (read-only, skip create/delete unless safe – delete only the sub-account created in 20.2)
21. **Configure** (local config only)
22. **Inbound** (CRUD for folders/inboxes/forward rules; messages/threads need received mail)
23. **Subscription Topics** (read-only topics; campaign, contact and suppression topic fields on accounts with and without topics)

---

Expand Down Expand Up @@ -450,4 +478,5 @@ Run tests in dependency order so earlier tests create resources needed by later
| Organizations | 3 | 5 |
| Configure | 1 | 2 |
| Inbound | 24 | 30 |
| **Total** | **~115** | **~139** |
| Subscription Topics | 2 | 17 |
| **Total** | **~117** | **~156** |
29 changes: 29 additions & 0 deletions internal/cmdutil/json_array.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package cmdutil

import (
"encoding/json"
"fmt"
"io"
"strings"
)

// ParseJSONArrayFlag strictly decodes the JSON array given to --flag: unknown
// keys and data after the array are errors. Callers validate the entries.
func ParseJSONArrayFlag[T any](flag, raw string) ([]T, error) {
if !strings.HasPrefix(strings.TrimSpace(raw), "[") {
return nil, fmt.Errorf("invalid --%s: must be a JSON array", flag)
}

dec := json.NewDecoder(strings.NewReader(raw))
dec.DisallowUnknownFields()

entries := []T{}
if err := dec.Decode(&entries); err != nil {
return nil, fmt.Errorf("invalid --%s JSON: %w", flag, err)
}
if _, err := dec.Token(); err != io.EOF {
return nil, fmt.Errorf("invalid --%s JSON: unexpected data after the array", flag)
}

return entries, nil
}
171 changes: 171 additions & 0 deletions internal/commands/contacts/contacts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"

Expand Down Expand Up @@ -498,3 +499,173 @@ func TestContactsExportStatus(t *testing.T) {
t.Errorf("expected output to contain 'completed', got:\n%s", output)
}
}

func TestContactsSendSubscriptionTopics(t *testing.T) {
topics := `[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"},{"subscription_topic_id":8,"domain_id":4322,"status":"subscribed"}]`
withTopics := map[string]interface{}{
"email": "x@y.com",
"subscription_topics": []interface{}{
map[string]interface{}{"subscription_topic_id": float64(7), "domain_id": float64(4321), "status": "unsubscribed"},
map[string]interface{}{"subscription_topic_id": float64(8), "domain_id": float64(4322), "status": "subscribed"},
},
}
withoutTopics := map[string]interface{}{"email": "x@y.com"}

// A topic-only update: the CLI still requires --email.
for _, tc := range []struct {
name string
args []string
contact map[string]interface{}
}{
{"create", []string{"create", "--email", "x@y.com", "--subscription-topics", topics}, withTopics},
{"update", []string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", topics}, withTopics},
{"create without topics", []string{"create", "--email", "x@y.com"}, withoutTopics},
{"update without topics", []string{"update", "--id", "abc-123", "--email", "x@y.com"}, withoutTopics},
} {
t.Run(tc.name, func(t *testing.T) {
f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) {
var payload map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
t.Fatalf("failed to decode body: %v", err)
}

want := map[string]interface{}{"contact": tc.contact}
if !reflect.DeepEqual(payload, want) {
t.Errorf("expected body %v, got %v", want, payload)
}

w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"data":{"id":"abc-123","email":"x@y.com","status":"subscribed"}}`))
})
defer cleanup()

cmd := contacts.NewCmdContacts(f)
cmd.SetArgs(tc.args)
cmd.SetOut(buf)

if err := cmd.Execute(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
})
}
}

// expectError runs the contacts command against handler and checks it fails with want.
func expectError(t *testing.T, handler http.HandlerFunc, args []string, want string) {
t.Helper()

f, _, cleanup := setupTest(handler)
defer cleanup()

cmd := contacts.NewCmdContacts(f)
cmd.SetArgs(args)
cmd.SilenceUsage = true
cmd.SilenceErrors = true

err := cmd.Execute()
if err == nil || !strings.Contains(err.Error(), want) {
t.Fatalf("expected error containing %q, got: %v", want, err)
}
}

func TestContactsInvalidSubscriptionTopics(t *testing.T) {
// Malformed JSON, unknown keys and trailing data are cmdutil.ParseJSONArrayFlag's,
// covered with --conditions in the forwardrules tests.
cases := []struct {
name string
value string
want string
}{
{"not an array", `{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}`, "invalid --subscription-topics: must be a JSON array"},
{"string id", `[{"subscription_topic_id":"7","domain_id":4321,"status":"subscribed"}]`, "invalid --subscription-topics JSON"},
{"missing topic", `[{"domain_id":4321,"status":"subscribed"}]`, "entry 1: subscription_topic_id must be greater than 0"},
{"missing domain", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"},{"subscription_topic_id":7,"status":"subscribed"}]`, "entry 2: domain_id must be greater than 0"},
{"bad status", `[{"subscription_topic_id":7,"domain_id":4321,"status":"active"}]`, "entry 1: status must be one of subscribed, unsubscribed"},
{"null entry", `[null]`, "entry 1: subscription_topic_id must be greater than 0"},
}

noRequest := func(w http.ResponseWriter, r *http.Request) {
t.Error("unexpected request")
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
expectError(t, noRequest, []string{"create", "--email", "x@y.com", "--subscription-topics", tc.value}, tc.want)
})
}
// update shares the parser; one case shows it is wired in.
t.Run("update", func(t *testing.T) {
expectError(t, noRequest, []string{"update", "--id", "abc-123", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7}]`},
"entry 1: domain_id must be greater than 0")
})
}

func TestContactsJSONKeepsContactAsIs(t *testing.T) {
withTopics := `{"id":"abc-123","email":"x@y.com","created_at":1700000000000,"updated_at":1700000000000,` +
`"list_ids":[],"status":"subscribed","fields":{"first_name":null},` +
`"subscription_topics":[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]}`
unreadable := `{"id":"abc-123","email":"x@y.com","list_ids":[],"status":"subscribed","fields":{},"subscription_topics":null}`
topicsOff := `{"id":"abc-123","email":"x@y.com","list_ids":[],"status":"subscribed","fields":{}}`

for _, tc := range []struct {
name string
contact string
args []string
}{
{"get with topics", withTopics, []string{"get", "--id", "abc-123"}},
{"get unreadable topics", unreadable, []string{"get", "--id", "abc-123"}},
{"get topics off", topicsOff, []string{"get", "--id", "abc-123"}},
{"create", withTopics, []string{"create", "--email", "x@y.com"}},
{"update", withTopics, []string{"update", "--id", "abc-123", "--email", "x@y.com"}},
} {
t.Run(tc.name, func(t *testing.T) {
f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"data":`+tc.contact+`}`)
})
defer cleanup()

viper.Set("output", "json")

cmd := contacts.NewCmdContacts(f)
cmd.SetArgs(tc.args)
cmd.SetOut(buf)

if err := cmd.Execute(); err != nil {
t.Fatalf("unexpected error: %v", err)
}

var got, want map[string]interface{}
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("output is not valid JSON: %v\noutput:\n%s", err, buf.String())
}
json.Unmarshal([]byte(tc.contact), &want)
if !reflect.DeepEqual(got, want) {
t.Errorf("expected the contact unchanged\nwant: %v\ngot: %v", want, got)
}
})
}
}

func TestContactsSubscriptionTopicsErrorsKeepMessage(t *testing.T) {
cases := []struct {
name string
status int
body string
want string
}{
{"topics off", http.StatusUnprocessableEntity, `{"errors":{"subscription_topics":["are not available for this account"]}}`, "are not available for this account"},
{"topics not saved", http.StatusServiceUnavailable, `{"errors":"The contact was saved, but its subscription topic preferences were not. Send them again in an update of contact abc-123."}`, "Send them again in an update of contact abc-123"},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(tc.status)
io.WriteString(w, tc.body)
}
expectError(t, handler, []string{"create", "--email", "x@y.com", "--subscription-topics", `[{"subscription_topic_id":7,"domain_id":4321,"status":"subscribed"}]`}, tc.want)
})
}
}
Loading
Loading