From 75f6aea1d4604286aab7eed715965db18d463e1c Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 14:48:43 +0100 Subject: [PATCH 1/6] print API errors as readable messages instead of the raw body Decisions: - errors is decoded as raw JSON: the API sends it as a string (the contacts 503), an array, or an object of strings or arrays (the 422s), and the map[string]string field failed on all but the last, so the raw body was printed - a decoded body lost its errors anyway, since Error() printed only the error field; now an object prints as sorted "field message" pairs, base errors without a field - GetRaw shares the decoding, so its JSON errors read the same Co-Authored-By: Claude Opus 5.5 --- internal/client/client.go | 8 +- internal/client/client_test.go | 53 +++++++++++- internal/client/errors.go | 82 +++++++++++++++++-- skills/mailtrap-cli/references/error-codes.md | 40 +++++++++ 4 files changed, 168 insertions(+), 15 deletions(-) diff --git a/internal/client/client.go b/internal/client/client.go index 60cecd9..21852af 100644 --- a/internal/client/client.go +++ b/internal/client/client.go @@ -85,11 +85,7 @@ func (c *Client) do(ctx context.Context, base BaseURL, method, path string, quer } if resp.StatusCode >= 400 { - apiErr := &APIError{StatusCode: resp.StatusCode} - if json.Unmarshal(respBody, apiErr) != nil { - apiErr.Message = string(respBody) - } - return apiErr + return newAPIError(resp.StatusCode, respBody) } if result != nil && len(respBody) > 0 { @@ -151,7 +147,7 @@ func (c *Client) GetRaw(ctx context.Context, base BaseURL, path string, query ur } if resp.StatusCode >= 400 { - return nil, &APIError{StatusCode: resp.StatusCode, Message: string(data)} + return nil, newAPIError(resp.StatusCode, data) } return data, nil diff --git a/internal/client/client_test.go b/internal/client/client_test.go index 5daf595..1764134 100644 --- a/internal/client/client_test.go +++ b/internal/client/client_test.go @@ -7,7 +7,6 @@ import ( "net/http" "net/http/httptest" "net/url" - "strings" "testing" ) @@ -325,16 +324,62 @@ func TestAPIError_JSONBody(t *testing.T) { if apiErr.Message != "validation failed" { t.Errorf("expected message %q, got %q", "validation failed", apiErr.Message) } - if v, ok := apiErr.Errors["name"]; !ok || v != "is required" { - t.Errorf("expected errors[name]=%q, got %v", "is required", apiErr.Errors) + if string(apiErr.Errors) != `{"name":"is required"}` { + t.Errorf("expected errors kept as sent, got %s", apiErr.Errors) } // Check Error() string output errStr := apiErr.Error() - if !strings.Contains(errStr, "422") || !strings.Contains(errStr, "validation failed") { + if errStr != "API error 422: validation failed; name is required" { t.Errorf("unexpected Error() output: %s", errStr) } } +func TestAPIError_ErrorsFormats(t *testing.T) { + cases := []struct { + name string + status int + body string + want string + }{ + {"error", http.StatusNotFound, `{"error":"Not Found"}`, "API error 404: Not Found"}, + {"errors string", http.StatusServiceUnavailable, + `{"errors":"The contact was saved, but its subscription topic preferences were not. Send them again in an update of contact abc-123."}`, + "API error 503: The contact was saved, but its subscription topic preferences were not. Send them again in an update of contact abc-123."}, + {"errors array", http.StatusBadRequest, `{"success":false,"errors":["'from' is required","'subject' is required"]}`, + "API error 400: 'from' is required; 'subject' is required"}, + {"errors object of arrays", http.StatusUnprocessableEntity, `{"errors":{"name":["can't be blank"],"email":["is invalid","is too long"]}}`, + "API error 422: email is invalid; email is too long; name can't be blank"}, + {"errors object of strings", http.StatusUnprocessableEntity, `{"errors":{"name":"is required"}}`, "API error 422: name is required"}, + {"base errors", http.StatusUnprocessableEntity, `{"errors":{"base":["Contacts limit reached"],"email":["is invalid"]}}`, + "API error 422: Contacts limit reached; email is invalid"}, + {"nested errors", http.StatusUnprocessableEntity, `{"errors":{"contacts":[{"email":["is invalid"]}],"limit":5000}}`, + "API error 422: contacts email is invalid; limit 5000"}, + {"null errors", http.StatusUnprocessableEntity, `{"errors":null}`, "API error 422"}, + {"plain text", http.StatusBadGateway, "bad gateway", "API error 502: bad gateway"}, + {"empty body", http.StatusForbidden, "", "API error 403"}, + } + + for _, tc := range cases { + _, c, base := setupTestServer(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tc.status) + io.WriteString(w, tc.body) + }) + + t.Run(tc.name, func(t *testing.T) { + err := c.Post(context.Background(), base, "/api/items", map[string]string{}, nil) + if err == nil || err.Error() != tc.want { + t.Errorf("expected %q, got %v", tc.want, err) + } + }) + t.Run(tc.name+" raw", func(t *testing.T) { + _, err := c.GetRaw(context.Background(), base, "/api/items/1/raw", nil) + if err == nil || err.Error() != tc.want { + t.Errorf("expected %q, got %v", tc.want, err) + } + }) + } +} + func TestAPIError_EmptyMessage(t *testing.T) { apiErr := &APIError{StatusCode: 403} expected := "API error 403" diff --git a/internal/client/errors.go b/internal/client/errors.go index ba6572a..0141bbb 100644 --- a/internal/client/errors.go +++ b/internal/client/errors.go @@ -1,16 +1,88 @@ package client -import "fmt" +import ( + "bytes" + "encoding/json" + "fmt" + "sort" + "strings" +) type APIError struct { StatusCode int - Message string `json:"error"` - Errors map[string]string `json:"errors,omitempty"` + Message string `json:"error"` + // Errors is the response's "errors" field as sent: a string, an array of + // messages, or an object mapping fields to a message or an array of them. + Errors json.RawMessage `json:"errors,omitempty"` +} + +// newAPIError builds the error for a failed response. A body that isn't a JSON +// object of this shape becomes the message as is. +func newAPIError(statusCode int, body []byte) *APIError { + apiErr := &APIError{StatusCode: statusCode} + if json.Unmarshal(body, apiErr) != nil { + return &APIError{StatusCode: statusCode, Message: string(body)} + } + return apiErr } func (e *APIError) Error() string { + messages := errorMessages(e.Errors) if e.Message != "" { - return fmt.Sprintf("API error %d: %s", e.StatusCode, e.Message) + messages = append([]string{e.Message}, messages...) + } + if len(messages) == 0 { + return fmt.Sprintf("API error %d", e.StatusCode) } - return fmt.Sprintf("API error %d", e.StatusCode) + return fmt.Sprintf("API error %d: %s", e.StatusCode, strings.Join(messages, "; ")) +} + +// errorMessages flattens an "errors" value into readable messages: a string as +// is, an array element by element, and an object as "field message" pairs +// sorted by field ("base" errors, which belong to no field, without one). +func errorMessages(raw json.RawMessage) []string { + raw = bytes.TrimSpace(raw) + if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { + return nil + } + + var text string + if json.Unmarshal(raw, &text) == nil { + if text == "" { + return nil + } + return []string{text} + } + + var list []json.RawMessage + if json.Unmarshal(raw, &list) == nil { + var messages []string + for _, item := range list { + messages = append(messages, errorMessages(item)...) + } + return messages + } + + var fields map[string]json.RawMessage + if json.Unmarshal(raw, &fields) == nil { + names := make([]string, 0, len(fields)) + for name := range fields { + names = append(names, name) + } + sort.Strings(names) + + var messages []string + for _, name := range names { + for _, message := range errorMessages(fields[name]) { + if name != "base" { + message = name + " " + message + } + messages = append(messages, message) + } + } + return messages + } + + // A number or a boolean prints as sent. + return []string{string(raw)} } diff --git a/skills/mailtrap-cli/references/error-codes.md b/skills/mailtrap-cli/references/error-codes.md index d3fc27e..fb30db0 100644 --- a/skills/mailtrap-cli/references/error-codes.md +++ b/skills/mailtrap-cli/references/error-codes.md @@ -27,6 +27,28 @@ Common API errors and their meanings when using the Mailtrap CLI. --- +## API Error Format + +A failed request prints one line: + +``` +Error: API error : +``` + +The message comes from the response body: + +| Body | Message | +|------|---------| +| `{"error": "Not Found"}` | `Not Found` | +| `{"errors": "Access forbidden"}` | `Access forbidden` | +| `{"errors": ["'from' is required", "'subject' is required"]}` | `'from' is required; 'subject' is required` | +| `{"errors": {"name": ["can't be blank"], "email": ["is invalid"]}}` | `email is invalid; name can't be blank` (one `field message` pair per message, sorted by field) | +| `{"errors": {"base": ["Contacts limit reached"]}}` | `Contacts limit reached` (`base` errors belong to no field) | +| empty | nothing: `API error 403` | +| not JSON | the body as is | + +--- + ## Common Error Patterns ### Missing required flag @@ -41,12 +63,30 @@ Error: API error 401: Unauthorized ``` **Fix:** Run `mailtrap configure --api-token ` or set `MAILTRAP_API_TOKEN`. +### Missing permission +``` +Error: API error 403: Access forbidden +``` +**Fix:** Use a token with access to the resource, or ask an account admin to grant it. + ### Resource not found ``` Error: API error 404: Not Found ``` **Fix:** Verify the resource ID exists. Use the corresponding `list` command to find valid IDs. +### Validation failed +``` +Error: API error 422: email is invalid +``` +**Fix:** Correct the named field and retry. Several invalid fields are joined with `; `. + +### Nothing to update +``` +Error: at least one attribute flag is required +``` +**Fix:** Commands such as `templates update` and `contacts update` send only the flags you pass; pass at least one besides `--id`. + ### Domain not verified ``` Error: API error 422: Domain is not verified From ef63aeafa287610e6dfebeb7137d0164b9b4394e Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 14:48:50 +0100 Subject: [PATCH 2/6] let contacts update change a contact without --email Decisions: - the API finds the contact by the ID in the path, so email is sent only when --email is passed, to change it; a topic-only update needs just --id and --subscription-topics - an update with no attribute flag fails before the request, with the error templates, domains and email-campaigns update give, since an empty contact changes nothing - the contacts reference listed flags the commands don't have (--list-id on import and export, --type/--data on create-event, --data-type on contact-fields update) and missed --list-ids-included, --list-ids-excluded, --unsubscribed and contact-lists list --search; the import eval expected the missing --list-id Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- docs/TEST_PLAN.md | 16 ++++--- internal/commands/contacts/contacts_test.go | 48 +++++++++++++++++-- internal/commands/contacts/update.go | 38 ++++++++------- skill-evals/mailtrap-cli/evals.json | 4 +- skills/mailtrap-cli/references/contacts.md | 26 ++++++---- .../references/subscription-topics.md | 2 +- 7 files changed, 94 insertions(+), 42 deletions(-) diff --git a/README.md b/README.md index 1bd07da..40da631 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,7 @@ mailtrap tokens reset --id 42 --expires-at never # Contacts mailtrap contacts create --email "user@example.com" --first-name "John" -mailtrap contacts update --id --email "user@example.com" \ +mailtrap contacts update --id \ --subscription-topics '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]' mailtrap contact-lists list mailtrap contact-lists list --search news diff --git a/docs/TEST_PLAN.md b/docs/TEST_PLAN.md index 7cbc6f6..1beff16 100644 --- a/docs/TEST_PLAN.md +++ b/docs/TEST_PLAN.md @@ -199,14 +199,16 @@ 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 ` | Single contact details | -| 10.3 | Update contact | `mailtrap contacts update --id --email "test@integration.com" --first-name "Test"` | Updated contact | +| 10.3 | Update contact | `mailtrap contacts update --id --first-name "Test"` | Updated contact; email unchanged | | 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 ` | Status details | | 10.7 | Export contacts | `mailtrap contacts export` | Export initiated | | 10.8 | Export status | `mailtrap contacts export-status --id ` | Status details | -| 10.9 | Create event | `mailtrap contacts create-event --id --type "purchase"` | Event created | +| 10.9 | Create event | `mailtrap contacts create-event --id --name "purchase"` | Event created | | 10.10 | Delete contact | `mailtrap contacts delete --id ` | Success message | +| 10.11 | Update without flags | `mailtrap contacts update --id ` | Error: `at least one attribute flag is required`; no request sent | +| 10.12 | Invalid email | `mailtrap contacts create --email "not-an-email"` | `Error: API error 422: email is invalid` | **Cleanup:** Delete created contact. @@ -394,14 +396,14 @@ Prerequisite: Send an email with an attachment to the sandbox. | 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 --from-local-part news --subject "Hi" --subscription-topic-id ` | TOPIC ID column shows the topic; `email-campaigns get --id -o json` has `subscription_topic_id` | | 23.8 | Campaign with uncovered topic | `mailtrap email-campaigns update --id --subscription-topic-id ` | `API error 422`, campaign unchanged | -| 23.9 | Contact topic preferences | `mailtrap contacts update --id --email --subscription-topics '[{"subscription_topic_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 --email --subscription-topics '[{"subscription_topic_id":,"status":"unsubscribed"}]'` | Error: `entry 1: domain_id must be greater than 0`; no request sent | +| 23.9 | Contact topic preferences | `mailtrap contacts update --id --subscription-topics '[{"subscription_topic_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 --subscription-topics '[{"subscription_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 -o json` | No `subscription_topics` key, no error | -| 23.16 | Topics off: contact write | `mailtrap contacts update --id --email --subscription-topics '[{"subscription_topic_id":1,"domain_id":,"status":"subscribed"}]'` | `API error 422` naming `subscription_topics` ("are not available for this account") | +| 23.16 | Topics off: contact write | `mailtrap contacts update --id --subscription-topics '[{"subscription_topic_id":1,"domain_id":,"status":"subscribed"}]'` | `API error 422: 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. @@ -465,7 +467,7 @@ Run tests in dependency order so earlier tests create resources needed by later | Email Logs | 2 | 4 | | Contact Lists | 5 | 6 | | Contact Fields | 5 | 6 | -| Contacts | 10 | 10 | +| Contacts | 10 | 12 | | Projects | 5 | 6 | | Sandboxes | 10 | 11 | | Sandbox Send | 2 | 3 | @@ -479,4 +481,4 @@ Run tests in dependency order so earlier tests create resources needed by later | Configure | 1 | 2 | | Inbound | 24 | 30 | | Subscription Topics | 2 | 17 | -| **Total** | **~117** | **~156** | +| **Total** | **~117** | **~158** | diff --git a/internal/commands/contacts/contacts_test.go b/internal/commands/contacts/contacts_test.go index c8f61db..d8254dd 100644 --- a/internal/commands/contacts/contacts_test.go +++ b/internal/commands/contacts/contacts_test.go @@ -291,6 +291,43 @@ func TestContactsUpdateWithListFlags(t *testing.T) { } } +func TestContactsUpdateWithoutEmail(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": map[string]interface{}{ + "fields": map[string]interface{}{"first_name": "Jane"}, + "unsubscribed": false, + }} + 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([]string{"update", "--id", "abc-123", "--first-name", "Jane", "--unsubscribed=false"}) + cmd.SetOut(buf) + + if err := cmd.Execute(); err != nil { + t.Fatalf("unexpected error: %v", err) + } +} + +func TestContactsUpdateNothingToUpdate(t *testing.T) { + noRequest := func(w http.ResponseWriter, r *http.Request) { + t.Error("unexpected request") + } + + expectError(t, noRequest, []string{"update", "--id", "abc-123"}, "at least one attribute flag is required") +} + func TestContactsDelete(t *testing.T) { f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodDelete { @@ -510,8 +547,8 @@ func TestContactsSendSubscriptionTopics(t *testing.T) { }, } withoutTopics := map[string]interface{}{"email": "x@y.com"} + onlyTopics := map[string]interface{}{"subscription_topics": withTopics["subscription_topics"]} - // A topic-only update: the CLI still requires --email. for _, tc := range []struct { name string args []string @@ -519,6 +556,7 @@ func TestContactsSendSubscriptionTopics(t *testing.T) { }{ {"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}, + {"topic-only update", []string{"update", "--id", "abc-123", "--subscription-topics", topics}, onlyTopics}, {"create without topics", []string{"create", "--email", "x@y.com"}, withoutTopics}, {"update without topics", []string{"update", "--id", "abc-123", "--email", "x@y.com"}, withoutTopics}, } { @@ -595,7 +633,7 @@ func TestContactsInvalidSubscriptionTopics(t *testing.T) { } // 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}]`}, + expectError(t, noRequest, []string{"update", "--id", "abc-123", "--subscription-topics", `[{"subscription_topic_id":7}]`}, "entry 1: domain_id must be greater than 0") }) } @@ -654,8 +692,10 @@ func TestContactsSubscriptionTopicsErrorsKeepMessage(t *testing.T) { 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"}, + {"topics off", http.StatusUnprocessableEntity, `{"errors":{"subscription_topics":["are not available for this account"]}}`, + "API error 422: subscription_topics 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."}`, + "API error 503: The contact was saved, but its subscription topic preferences were not. Send them again in an update of contact abc-123."}, } for _, tc := range cases { diff --git a/internal/commands/contacts/update.go b/internal/commands/contacts/update.go index f17e94f..dc81c7c 100644 --- a/internal/commands/contacts/update.go +++ b/internal/commands/contacts/update.go @@ -28,12 +28,11 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { if err := cmdutil.RequireFlag("id", contactID); err != nil { return err } - if err := cmdutil.RequireFlag("email", email); err != nil { - return err - } - contactData := map[string]interface{}{ - "email": email, + // The API finds the contact by its ID, so the email is sent only to change it. + contactData := map[string]interface{}{} + if cmd.Flags().Changed("email") { + contactData["email"] = email } if cmd.Flags().Changed("subscription-topics") { parsed, err := parseSubscriptionTopics(subscriptionTopics) @@ -43,18 +42,6 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { contactData["subscription_topics"] = parsed } - c, err := f.NewClient() - if err != nil { - return err - } - - _, err = config.RequireAccountID() - if err != nil { - return err - } - - path := cmdutil.AccountPath("contacts", fmt.Sprintf("%s", contactID)) - fields := map[string]interface{}{} if firstName != "" { fields["first_name"] = firstName @@ -75,6 +62,21 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { if cmd.Flags().Changed("unsubscribed") { contactData["unsubscribed"] = unsubscribed } + if len(contactData) == 0 { + return fmt.Errorf("at least one attribute flag is required") + } + + c, err := f.NewClient() + if err != nil { + return err + } + + _, err = config.RequireAccountID() + if err != nil { + return err + } + + path := cmdutil.AccountPath("contacts", fmt.Sprintf("%s", contactID)) body := map[string]interface{}{ "contact": contactData, @@ -91,7 +93,7 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { } cmd.Flags().StringVar(&contactID, "id", "", "Contact ID (required)") - cmd.Flags().StringVar(&email, "email", "", "Contact email (required)") + cmd.Flags().StringVar(&email, "email", "", "Contact email") cmd.Flags().StringVar(&firstName, "first-name", "", "Contact first name") cmd.Flags().StringVar(&lastName, "last-name", "", "Contact last name") cmd.Flags().IntSliceVar(&listIDsIncluded, "list-ids-included", nil, "List IDs to subscribe to") diff --git a/skill-evals/mailtrap-cli/evals.json b/skill-evals/mailtrap-cli/evals.json index 63ec3c3..e033ac0 100644 --- a/skill-evals/mailtrap-cli/evals.json +++ b/skill-evals/mailtrap-cli/evals.json @@ -103,8 +103,8 @@ "prompt": "Import contacts from my contacts.json file into list 5", "expected": { "command": "contacts import", - "flags": ["--file", "--list-id"], - "must_not_contain": ["create", "export"] + "flags": ["--file"], + "must_not_contain": ["create", "export", "--list-id"] } }, { diff --git a/skills/mailtrap-cli/references/contacts.md b/skills/mailtrap-cli/references/contacts.md index 2d42763..f3fec0d 100644 --- a/skills/mailtrap-cli/references/contacts.md +++ b/skills/mailtrap-cli/references/contacts.md @@ -44,11 +44,16 @@ Update an existing contact. | Flag | Type | Required | Description | |------|------|----------|-------------| | `--id` | string | Yes | Contact ID | -| `--email` | string | Yes | Contact email address, also for a topic-only update (pass the current one to keep it) | +| `--email` | string | No | New email address | | `--first-name` | string | No | New first name | | `--last-name` | string | No | New last name | +| `--list-ids-included` | int[] | No | List IDs to add the contact to | +| `--list-ids-excluded` | int[] | No | List IDs to remove the contact from | +| `--unsubscribed` | bool | No | Unsubscribe the contact (`--unsubscribed=false` subscribes it again) | | `--subscription-topics` | string | No | Subscription topic preferences as a JSON array, as for `contacts create`; pairs left out keep their status | +Only supplied flags are updated; omitted fields remain unchanged. At least one flag besides `--id` is required, so a topic-only update needs just `--id` and `--subscription-topics`. + --- ## contacts delete @@ -68,12 +73,11 @@ Import contacts from a JSON file. | Flag | Type | Required | Description | |------|------|----------|-------------| | `--file` | string | Yes | Path to JSON file with contact data | -| `--list-id` | int | No | List ID to import contacts into | -The file is posted as is. Each contact may carry `subscription_topics`, with the same entries as `contacts create --subscription-topics`: +The file is posted as is. Lists are set per contact in the file: `list_ids_included` adds the contact to lists and `list_ids_excluded` removes it from them. Each contact may also carry `subscription_topics`, with the same entries as `contacts create --subscription-topics`: ```json -{"contacts": [{"email": "user@example.com", "subscription_topics": [{"subscription_topic_id": 7, "domain_id": 4321, "status": "unsubscribed"}]}]} +{"contacts": [{"email": "user@example.com", "list_ids_included": [55], "subscription_topics": [{"subscription_topic_id": 7, "domain_id": 4321, "status": "unsubscribed"}]}]} ``` --- @@ -84,7 +88,8 @@ Export contacts. | Flag | Type | Required | Description | |------|------|----------|-------------| -| `--list-id` | int | No | List ID to export from | +| `--list-ids` | int[] | No | Export only contacts in these lists | +| `--status` | string | No | Export only contacts with this subscription status: `subscribed`, `unsubscribed` | --- @@ -115,8 +120,8 @@ Create a custom event for a contact (used for automation triggers). | Flag | Type | Required | Description | |------|------|----------|-------------| | `--id` | string | Yes | Contact ID | -| `--type` | string | Yes | Event type name | -| `--data` | string | No | Event data as JSON string | +| `--name` | string | Yes | Event name (max 255 characters) | +| `--params` | string | No | Event params as a JSON object | --- @@ -124,7 +129,9 @@ Create a custom event for a contact (used for automation triggers). List all contact lists. -No additional flags. +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--search` | string | No | Filter by name (case-insensitive prefix match) | --- @@ -207,9 +214,10 @@ Update a custom contact field. |------|------|----------|-------------| | `--id` | string | Yes | Contact field ID | | `--name` | string | No | New field name | -| `--data-type` | string | No | New data type | | `--merge-tag` | string | No | New merge tag | +The data type can't be changed. + --- ## contact-fields delete diff --git a/skills/mailtrap-cli/references/subscription-topics.md b/skills/mailtrap-cli/references/subscription-topics.md index 91fa2ea..066f1e4 100644 --- a/skills/mailtrap-cli/references/subscription-topics.md +++ b/skills/mailtrap-cli/references/subscription-topics.md @@ -48,7 +48,7 @@ A campaign's topic can be changed but not removed. On an account without subscri `contacts create` and `contacts update` take `--subscription-topics`, a JSON array with one entry per topic and domain. See [contacts.md](contacts.md). ```bash -mailtrap contacts update --id --email user@example.com \ +mailtrap contacts update --id \ --subscription-topics '[{"subscription_topic_id":7,"domain_id":4321,"status":"unsubscribed"}]' ``` From 26a497793da47fd5fccd062042043dc5f8d41401 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 14:48:50 +0100 Subject: [PATCH 3/6] add email-campaigns and webhooks references to the CLI skill Decisions: - both groups had commands but no Command Groups row or reference, so agents guessed their flags; the references are read from the flag definitions - the webhook type table follows the API's validations, so an agent passes only the flags each type accepts Co-Authored-By: Claude Opus 5.5 --- skills/mailtrap-cli/SKILL.md | 6 +- .../references/email-campaigns.md | 157 ++++++++++++++++++ skills/mailtrap-cli/references/webhooks.md | 90 ++++++++++ 3 files changed, 251 insertions(+), 2 deletions(-) create mode 100644 skills/mailtrap-cli/references/email-campaigns.md create mode 100644 skills/mailtrap-cli/references/webhooks.md diff --git a/skills/mailtrap-cli/SKILL.md b/skills/mailtrap-cli/SKILL.md index 1e55f2f..3393200 100644 --- a/skills/mailtrap-cli/SKILL.md +++ b/skills/mailtrap-cli/SKILL.md @@ -2,7 +2,7 @@ The `mailtrap` CLI is the official command-line interface for the Mailtrap email platform. It covers transactional/bulk email sending, sandboxes, domain management, templates, -contacts, statistics, and account administration. +contacts, email campaigns, webhooks, statistics, and account administration. ## Authentication @@ -50,7 +50,7 @@ A `null` cursor means there are no more pages. `suppressions list` and `messages - **Repeated flags**: flags like `--to`, `--cc`, `--bcc`, `--domain-ids` can be specified multiple times - **Batch operations**: use `--file path/to/payload.json` with a JSON array of email objects - **Config priority**: CLI flags > environment variables > config file -- **Exit codes**: 0 on success, 1 on error (with descriptive message) +- **Exit codes**: 0 on success, 1 on error (with descriptive message). API errors print as `API error : `; see [error-codes.md](references/error-codes.md) - **Naming**: sandboxes were formerly called inboxes, and domains were sending domains. A user asking about an "inbox" usually means a sandbox (`sandboxes`, `--sandbox-id`) unless they mean Email Inbound (`inbound`). API paths, JSON keys and token resource types keep the old names (`/inboxes`, `sending_domain_id`, `"inbox"`, `"sending_domain"`) - **API base**: most requests go to `https://mailtrap.io/api/accounts/{account-id}/...`. Several groups do not and take no `--account-id`: `inbound` (`/api/inbound/...`), `company-info` (`/api/domains/{domain-id}/company_info`), `tracking-opt-outs` (`/api/tracking_opt_outs`), `email-campaigns` (`/api/email_campaigns`), `subscription-topics` (`/api/subscription_topics`) and `organizations` (`/api/organizations/...`). `send` and `sandbox-send` go to their own hosts entirely. @@ -68,6 +68,7 @@ A `null` cursor means there are no more pages. `suppressions list` and `messages | `contacts` | Contact management & import/export | [contacts.md](references/contacts.md) | | `contact-lists` | Contact list CRUD | [contacts.md](references/contacts.md) | | `contact-fields` | Custom contact fields | [contacts.md](references/contacts.md) | +| `email-campaigns` | Email campaign CRUD, sending lifecycle & stats | [email-campaigns.md](references/email-campaigns.md) | | `subscription-topics` | Subscription topics, and the topic fields on campaigns, contacts and suppressions | [subscription-topics.md](references/subscription-topics.md) | | `sandbox-send` | Sending emails to a sandbox | [sandbox.md](references/sandbox.md) | | `projects` | Sandbox project management | [sandbox.md](references/sandbox.md) | @@ -82,6 +83,7 @@ A `null` cursor means there are no more pages. `suppressions list` and `messages | `organizations` | Sub-account management | [accounts.md](references/accounts.md) | | `suppressions` | Suppression list management | [domains.md](references/domains.md) | | `tracking-opt-outs` | Open and click tracking opt-outs | [domains.md](references/domains.md) | +| `webhooks` | Webhooks for sending, campaign, audit log & inbound events | [webhooks.md](references/webhooks.md) | ## Gotchas diff --git a/skills/mailtrap-cli/references/email-campaigns.md b/skills/mailtrap-cli/references/email-campaigns.md new file mode 100644 index 0000000..d6984e9 --- /dev/null +++ b/skills/mailtrap-cli/references/email-campaigns.md @@ -0,0 +1,157 @@ +# email-campaigns + +Detailed flag specifications for `mailtrap email-campaigns` commands. + +`email-campaigns` commands are token-scoped: they take no `--account-id` (requests go to `/api/email_campaigns`). + +A campaign starts as a draft. Only a draft can be updated, deleted, started or scheduled; a scheduled campaign can be cancelled or reset to draft, and a sending one terminated. + +**Output:** Campaign commands print a table with ID, name, state, domain, recipient count, topic ID and creation time. With `--output json`, the campaign as the API returns it. + +--- + +## email-campaigns list + +List the account's email campaigns, one page at a time. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--per-page` | int | No | Number of campaigns per page (default 50, max 100) | +| `--search` | string | No | Filter campaigns by name | +| `--token` | int | No | Page number to retrieve (page-token pagination) | + +**Output:** Table of campaigns, followed by `Next page: --token N` when more pages exist; repeat `--search` and `--per-page` with it. With `--output json`, the full response object is printed: `.data` holds the campaigns and `.pagination.next_token` the next page (`null` on the last page). + +--- + +## email-campaigns get + +Get an email campaign. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | + +--- + +## email-campaigns create + +Create a draft email campaign. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--name` | string | Yes | Campaign name | +| `--domain-id` | int | Yes | ID of the verified domain to send from (see `domains list`) | +| `--from-local-part` | string | Yes | Local part (before the @) of the From address | +| `--subject` | string | Yes | Email subject line | +| `--from-display-name` | string | No | Display name shown in the From header | +| `--reply-to-display-name` | string | No | Reply-To display name | +| `--reply-to-local-part` | string | No | Reply-To local part (before the @) | +| `--reply-to-domain` | string | No | Reply-To domain | +| `--body-html` | string | No | HTML body of the email (the design) | +| `--body-text` | string | No | Plain-text alternative of the email body | +| `--merge-tags` | string[] | No | Merge tag names used in the content (comma-separated), without `{{ }}` | +| `--delivery-mode` | string | No | Delivery mode: `rapid`, `gradual` | +| `--emails-per-hour` | int | No | Emails per hour when the delivery mode is `gradual` | +| `--contact-list-ids` | int[] | No | Contact list IDs to send to (comma-separated) | +| `--contact-segment-ids` | int[] | No | Contact segment IDs to send to (comma-separated) | +| `--subscription-topic-id` | int | No | Subscription topic ID; see [subscription-topics.md](subscription-topics.md) | + +**Example:** +```bash +mailtrap email-campaigns create --name "Spring Sale" --domain-id 4321 \ + --from-local-part news --subject "Spring is here" \ + --body-html '

Hi {{first_name}}!

Unsubscribe' \ + --merge-tags first_name --contact-list-ids 55,56 +``` + +--- + +## email-campaigns update + +Update a draft email campaign. Takes the same flags as `create`, all optional, plus: + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | +| `--clear-contact-lists` | bool | No | Remove all contact lists from the audience (not with `--contact-list-ids`) | +| `--clear-contact-segments` | bool | No | Remove all contact segments from the audience (not with `--contact-segment-ids`) | + +Only supplied flags are updated; at least one is required. `--contact-list-ids` and `--contact-segment-ids` replace the whole audience list rather than adding to it. + +```bash +mailtrap email-campaigns update --id 4567 --subject "Spring is finally here" --contact-list-ids 55,56 +``` + +--- + +## email-campaigns delete + +Delete a draft email campaign. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | + +--- + +## email-campaigns start + +Start sending a draft email campaign now. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | + +--- + +## email-campaigns schedule + +Schedule a draft email campaign. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | +| `--datetime` | string | Yes | When to send the campaign, ISO 8601 (e.g. `2030-01-01T09:00:00Z`) | + +--- + +## email-campaigns cancel + +Cancel a scheduled email campaign. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | + +--- + +## email-campaigns reset + +Reset a scheduled email campaign to draft. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | + +--- + +## email-campaigns terminate + +Terminate a campaign that is sending. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | + +--- + +## email-campaigns stats + +Get an email campaign's statistics: sent, delivered, opens, clicks, bounces, spam complaints and unsubscribes, with their rates. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Email campaign ID | +| `--start-date` | string | No | Start of the aggregation window (`YYYY-MM-DD`) | +| `--end-date` | string | No | End of the aggregation window (`YYYY-MM-DD`) | diff --git a/skills/mailtrap-cli/references/webhooks.md b/skills/mailtrap-cli/references/webhooks.md new file mode 100644 index 0000000..05cbc14 --- /dev/null +++ b/skills/mailtrap-cli/references/webhooks.md @@ -0,0 +1,90 @@ +# webhooks + +Detailed flag specifications for `mailtrap webhooks` commands. + +A webhook sends events to a URL. Its type decides which events and flags apply: + +| Type | Events | Flags | +|------|--------|-------| +| `email_sending` | the `--event-types` you list | `--sending-stream` and `--event-types` required; `--domain-id` optional | +| `campaigns` | the `--event-types` you list | `--event-types` required; `--domain-id` optional | +| `audit_log` | account activity | no `--sending-stream`, `--domain-id` or `--event-types` | +| `inbound_receiving` | Email Inbound messages received | no `--sending-stream`, `--domain-id` or `--event-types`; `--inbound-inbox-id` optional | + +Event types: `delivery`, `soft_bounce`, `bounce`, `suspension`, `unsubscribe`, `open`, `spam_complaint`, `click`, `reject`, and `subscription_preferences_update` (bulk `email_sending` and `campaigns` webhooks only). The CLI passes them to the API unchecked. + +**Output:** Webhook commands print a table with ID, URL, type, active, payload format, sending stream, domain ID, inbound inbox ID and event types. + +--- + +## webhooks list + +List the account's webhooks. + +No additional flags. + +--- + +## webhooks get + +Get a webhook. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Webhook ID | + +--- + +## webhooks create + +Create a webhook. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--url` | string | Yes | URL the events are sent to | +| `--type` | string | Yes | Webhook type: `email_sending`, `campaigns`, `audit_log`, `inbound_receiving` | +| `--active` | bool | No | Whether the webhook is active (default `true`) | +| `--payload-format` | string | No | Payload format: `json`, `jsonlines` | +| `--sending-stream` | string | No | Sending stream: `transactional`, `bulk` (`email_sending` only) | +| `--event-types` | string[] | No | Event types (comma-separated) | +| `--domain-id` | int | No | Domain ID to scope the webhook to (`email_sending` and `campaigns`) | +| `--inbound-inbox-id` | int | No | Email Inbound inbox ID to scope the webhook to (`inbound_receiving` only; omit for all inboxes) | + +**Output:** The webhook, with a SIGNING SECRET column. The signing secret is returned only here; store it to verify the events' signatures. + +**Example:** +```bash +mailtrap webhooks create --url "https://example.com/hooks" --type email_sending \ + --sending-stream transactional --event-types delivery,bounce +``` + +--- + +## webhooks update + +Update a webhook. The type, sending stream and domain can't be changed. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Webhook ID | +| `--url` | string | No | New URL | +| `--active` | bool | No | Whether the webhook is active (`--active=false` pauses it) | +| `--payload-format` | string | No | Payload format: `json`, `jsonlines` | +| `--event-types` | string[] | No | Event types (comma-separated); replaces the current list | +| `--inbound-inbox-id` | int | No | Email Inbound inbox ID to scope the webhook to (`inbound_receiving` only) | + +Only supplied flags are updated; omitted fields remain unchanged. + +```bash +mailtrap webhooks update --id 1 --active=false +``` + +--- + +## webhooks delete + +Delete a webhook. + +| Flag | Type | Required | Description | +|------|------|----------|-------------| +| `--id` | string | Yes | Webhook ID | From 0e69b3ee0265c5149eeffe7d714552ca599fff59 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 14:55:48 +0100 Subject: [PATCH 4/6] keep the body of a JSON error that has no error or errors field Decisions: - GetRaw printed every error body before it shared the decoding, so a JSON body without either field would otherwise lose its text; do() gains the same fallback, where such bodies printed a bare status - the 401 and 429 examples now quote what the API sends (Incorrect API token, Throttled) - webhooks update sends an empty update when given only --id, which the API answers with 400 Bad Request; the reference says so Co-Authored-By: Claude Opus 5.5 --- internal/client/client_test.go | 4 +++- internal/client/errors.go | 4 ++-- skills/mailtrap-cli/references/error-codes.md | 6 +++--- skills/mailtrap-cli/references/webhooks.md | 2 +- 4 files changed, 9 insertions(+), 7 deletions(-) diff --git a/internal/client/client_test.go b/internal/client/client_test.go index 1764134..6b30043 100644 --- a/internal/client/client_test.go +++ b/internal/client/client_test.go @@ -354,7 +354,9 @@ func TestAPIError_ErrorsFormats(t *testing.T) { "API error 422: Contacts limit reached; email is invalid"}, {"nested errors", http.StatusUnprocessableEntity, `{"errors":{"contacts":[{"email":["is invalid"]}],"limit":5000}}`, "API error 422: contacts email is invalid; limit 5000"}, - {"null errors", http.StatusUnprocessableEntity, `{"errors":null}`, "API error 422"}, + {"null errors", http.StatusNotFound, `{"error":"Not Found","errors":null}`, "API error 404: Not Found"}, + {"other JSON", http.StatusForbidden, `{"message":"Access to this inbox is forbidden"}`, + `API error 403: {"message":"Access to this inbox is forbidden"}`}, {"plain text", http.StatusBadGateway, "bad gateway", "API error 502: bad gateway"}, {"empty body", http.StatusForbidden, "", "API error 403"}, } diff --git a/internal/client/errors.go b/internal/client/errors.go index 0141bbb..d9d658d 100644 --- a/internal/client/errors.go +++ b/internal/client/errors.go @@ -17,10 +17,10 @@ type APIError struct { } // newAPIError builds the error for a failed response. A body that isn't a JSON -// object of this shape becomes the message as is. +// object of this shape, or carries no message in it, becomes the message as is. func newAPIError(statusCode int, body []byte) *APIError { apiErr := &APIError{StatusCode: statusCode} - if json.Unmarshal(body, apiErr) != nil { + if json.Unmarshal(body, apiErr) != nil || (apiErr.Message == "" && len(errorMessages(apiErr.Errors)) == 0) { return &APIError{StatusCode: statusCode, Message: string(body)} } return apiErr diff --git a/skills/mailtrap-cli/references/error-codes.md b/skills/mailtrap-cli/references/error-codes.md index fb30db0..cdef38e 100644 --- a/skills/mailtrap-cli/references/error-codes.md +++ b/skills/mailtrap-cli/references/error-codes.md @@ -45,7 +45,7 @@ The message comes from the response body: | `{"errors": {"name": ["can't be blank"], "email": ["is invalid"]}}` | `email is invalid; name can't be blank` (one `field message` pair per message, sorted by field) | | `{"errors": {"base": ["Contacts limit reached"]}}` | `Contacts limit reached` (`base` errors belong to no field) | | empty | nothing: `API error 403` | -| not JSON | the body as is | +| anything else | the body as is | --- @@ -59,7 +59,7 @@ Error: required flag(s) "--from", "--to", "--subject" not set ### Invalid API token ``` -Error: API error 401: Unauthorized +Error: API error 401: Incorrect API token ``` **Fix:** Run `mailtrap configure --api-token ` or set `MAILTRAP_API_TOKEN`. @@ -95,7 +95,7 @@ Error: API error 422: Domain is not verified ### Rate limited ``` -Error: API error 429: Too Many Requests +Error: API error 429: Throttled ``` **Fix:** Wait before retrying. Consider using batch endpoints for high-volume sends. diff --git a/skills/mailtrap-cli/references/webhooks.md b/skills/mailtrap-cli/references/webhooks.md index 05cbc14..c451fe7 100644 --- a/skills/mailtrap-cli/references/webhooks.md +++ b/skills/mailtrap-cli/references/webhooks.md @@ -73,7 +73,7 @@ Update a webhook. The type, sending stream and domain can't be changed. | `--event-types` | string[] | No | Event types (comma-separated); replaces the current list | | `--inbound-inbox-id` | int | No | Email Inbound inbox ID to scope the webhook to (`inbound_receiving` only) | -Only supplied flags are updated; omitted fields remain unchanged. +Only supplied flags are updated; omitted fields remain unchanged. Pass at least one besides `--id`: the API answers an empty update with `API error 400: Bad Request`. ```bash mailtrap webhooks update --id 1 --active=false From 612884baae69820e5bd6a3cc91e851a79d9a44b7 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 14:58:35 +0100 Subject: [PATCH 5/6] build an API error's message once, when the response is read Decisions: - APIError kept the raw errors and flattened them on every Error() call, while newAPIError flattened them again to pick the fallback; one pass in newAPIError leaves APIError as status and message, as before - the update-without-email case joins the existing request body table, and the contacts error test keeps its substrings, since the client tests own the format Co-Authored-By: Claude Opus 5.5 --- internal/client/client_test.go | 7 +-- internal/client/errors.go | 47 ++++++++++----------- internal/commands/contacts/contacts_test.go | 37 ++-------------- internal/commands/contacts/update.go | 2 +- 4 files changed, 30 insertions(+), 63 deletions(-) diff --git a/internal/client/client_test.go b/internal/client/client_test.go index 6b30043..af37179 100644 --- a/internal/client/client_test.go +++ b/internal/client/client_test.go @@ -321,11 +321,8 @@ func TestAPIError_JSONBody(t *testing.T) { if apiErr.StatusCode != 422 { t.Errorf("expected status 422, got %d", apiErr.StatusCode) } - if apiErr.Message != "validation failed" { - t.Errorf("expected message %q, got %q", "validation failed", apiErr.Message) - } - if string(apiErr.Errors) != `{"name":"is required"}` { - t.Errorf("expected errors kept as sent, got %s", apiErr.Errors) + if apiErr.Message != "validation failed; name is required" { + t.Errorf("expected message %q, got %q", "validation failed; name is required", apiErr.Message) } // Check Error() string output errStr := apiErr.Error() diff --git a/internal/client/errors.go b/internal/client/errors.go index d9d658d..dd567d6 100644 --- a/internal/client/errors.go +++ b/internal/client/errors.go @@ -4,37 +4,42 @@ import ( "bytes" "encoding/json" "fmt" - "sort" + "maps" + "slices" "strings" ) type APIError struct { StatusCode int - Message string `json:"error"` - // Errors is the response's "errors" field as sent: a string, an array of - // messages, or an object mapping fields to a message or an array of them. - Errors json.RawMessage `json:"errors,omitempty"` + Message string } -// newAPIError builds the error for a failed response. A body that isn't a JSON -// object of this shape, or carries no message in it, becomes the message as is. +// newAPIError builds the error for a failed response. Its message is the body's +// "error" text followed by its "errors" (see errorMessages), joined with "; ". +// A body that isn't a JSON object of this shape, or carries no message in it, +// becomes the message as is. func newAPIError(statusCode int, body []byte) *APIError { - apiErr := &APIError{StatusCode: statusCode} - if json.Unmarshal(body, apiErr) != nil || (apiErr.Message == "" && len(errorMessages(apiErr.Errors)) == 0) { - return &APIError{StatusCode: statusCode, Message: string(body)} + var parsed struct { + Error string `json:"error"` + Errors json.RawMessage `json:"errors"` } - return apiErr + if json.Unmarshal(body, &parsed) == nil { + messages := errorMessages(parsed.Errors) + if parsed.Error != "" { + messages = append([]string{parsed.Error}, messages...) + } + if len(messages) > 0 { + return &APIError{StatusCode: statusCode, Message: strings.Join(messages, "; ")} + } + } + return &APIError{StatusCode: statusCode, Message: string(body)} } func (e *APIError) Error() string { - messages := errorMessages(e.Errors) if e.Message != "" { - messages = append([]string{e.Message}, messages...) + return fmt.Sprintf("API error %d: %s", e.StatusCode, e.Message) } - if len(messages) == 0 { - return fmt.Sprintf("API error %d", e.StatusCode) - } - return fmt.Sprintf("API error %d: %s", e.StatusCode, strings.Join(messages, "; ")) + return fmt.Sprintf("API error %d", e.StatusCode) } // errorMessages flattens an "errors" value into readable messages: a string as @@ -65,14 +70,8 @@ func errorMessages(raw json.RawMessage) []string { var fields map[string]json.RawMessage if json.Unmarshal(raw, &fields) == nil { - names := make([]string, 0, len(fields)) - for name := range fields { - names = append(names, name) - } - sort.Strings(names) - var messages []string - for _, name := range names { + for _, name := range slices.Sorted(maps.Keys(fields)) { for _, message := range errorMessages(fields[name]) { if name != "base" { message = name + " " + message diff --git a/internal/commands/contacts/contacts_test.go b/internal/commands/contacts/contacts_test.go index d8254dd..6e653be 100644 --- a/internal/commands/contacts/contacts_test.go +++ b/internal/commands/contacts/contacts_test.go @@ -291,35 +291,6 @@ func TestContactsUpdateWithListFlags(t *testing.T) { } } -func TestContactsUpdateWithoutEmail(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": map[string]interface{}{ - "fields": map[string]interface{}{"first_name": "Jane"}, - "unsubscribed": false, - }} - 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([]string{"update", "--id", "abc-123", "--first-name", "Jane", "--unsubscribed=false"}) - cmd.SetOut(buf) - - if err := cmd.Execute(); err != nil { - t.Fatalf("unexpected error: %v", err) - } -} - func TestContactsUpdateNothingToUpdate(t *testing.T) { noRequest := func(w http.ResponseWriter, r *http.Request) { t.Error("unexpected request") @@ -548,6 +519,7 @@ func TestContactsSendSubscriptionTopics(t *testing.T) { } withoutTopics := map[string]interface{}{"email": "x@y.com"} onlyTopics := map[string]interface{}{"subscription_topics": withTopics["subscription_topics"]} + withoutEmail := map[string]interface{}{"fields": map[string]interface{}{"first_name": "Jane"}, "unsubscribed": false} for _, tc := range []struct { name string @@ -559,6 +531,7 @@ func TestContactsSendSubscriptionTopics(t *testing.T) { {"topic-only update", []string{"update", "--id", "abc-123", "--subscription-topics", topics}, onlyTopics}, {"create without topics", []string{"create", "--email", "x@y.com"}, withoutTopics}, {"update without topics", []string{"update", "--id", "abc-123", "--email", "x@y.com"}, withoutTopics}, + {"update without email", []string{"update", "--id", "abc-123", "--first-name", "Jane", "--unsubscribed=false"}, withoutEmail}, } { t.Run(tc.name, func(t *testing.T) { f, buf, cleanup := setupTest(func(w http.ResponseWriter, r *http.Request) { @@ -692,10 +665,8 @@ func TestContactsSubscriptionTopicsErrorsKeepMessage(t *testing.T) { body string want string }{ - {"topics off", http.StatusUnprocessableEntity, `{"errors":{"subscription_topics":["are not available for this account"]}}`, - "API error 422: subscription_topics 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."}`, - "API error 503: The contact was saved, but its subscription topic preferences were not. Send them again in an update of contact abc-123."}, + {"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 { diff --git a/internal/commands/contacts/update.go b/internal/commands/contacts/update.go index dc81c7c..946e7a6 100644 --- a/internal/commands/contacts/update.go +++ b/internal/commands/contacts/update.go @@ -76,7 +76,7 @@ func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command { return err } - path := cmdutil.AccountPath("contacts", fmt.Sprintf("%s", contactID)) + path := cmdutil.AccountPath("contacts", contactID) body := map[string]interface{}{ "contact": contactData, From b47ab4d97c2852543cc1a3a295e132b07cc032ea Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Tue, 24 Nov 2026 00:26:22 +0100 Subject: [PATCH 6/6] document what email-campaigns delete and stats print Decisions: - The file's general output note says campaign commands print the campaign; delete prints a fixed line even with --output json and stats prints statistics, so scripts following the general note would misread both - Put each note in its command's section, as list already does, instead of listing exceptions in the general note Co-Authored-By: Claude Opus 5.5 --- skills/mailtrap-cli/references/email-campaigns.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/skills/mailtrap-cli/references/email-campaigns.md b/skills/mailtrap-cli/references/email-campaigns.md index d6984e9..6b4ca36 100644 --- a/skills/mailtrap-cli/references/email-campaigns.md +++ b/skills/mailtrap-cli/references/email-campaigns.md @@ -93,6 +93,8 @@ Delete a draft email campaign. |------|------|----------|-------------| | `--id` | string | Yes | Email campaign ID | +**Output:** `Email campaign deleted successfully.`, also with `--output json`. + --- ## email-campaigns start @@ -155,3 +157,5 @@ Get an email campaign's statistics: sent, delivered, opens, clicks, bounces, spa | `--id` | string | Yes | Email campaign ID | | `--start-date` | string | No | Start of the aggregation window (`YYYY-MM-DD`) | | `--end-date` | string | No | End of the aggregation window (`YYYY-MM-DD`) | + +**Output:** The statistics, not the campaign: counts and rates in a table, or the response's `data` object with `--output json`.