Usage | laravel-mailcoach-sdk-go | Spatie       

 SPATIE  

laravel-mailcoach-sdk-go
========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-mailcoach-sdk-go](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1/introduction)
- [ Installation and setup ](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1/testing)
- [ Releasing ](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1/releasing)
- [ Changelog ](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1/changelog)
- [ Support us ](https://spatie.be/docs/laravel-mailcoach-sdk-go/v1/support-us)

 Usage
=====

###  On this page 

1. [ Handling pagination ](#content-handling-pagination)
2. [ Working with email lists ](#content-working-with-email-lists)
3. [ Working with subscribers ](#content-working-with-subscribers)
4. [ Working with models ](#content-working-with-models)
5. [ Working with campaigns ](#content-working-with-campaigns)
6. [ Working with automations ](#content-working-with-automations)
7. [ Working with templates ](#content-working-with-templates)
8. [ Working with transactional mails ](#content-working-with-transactional-mails)
9. [ Custom endpoints and resources ](#content-custom-endpoints-and-resources)
10. [ Handling failures ](#content-handling-failures)
11. [ Differences from PHP ](#content-differences-from-php)

Use the client directly, or `mailcoachlaravel.From(r)` inside a Laravel handler. All network operations take a `context.Context` as the first argument and return an error. Pass `r` in a Laravel handler, or the job or listener's `ctx`.

Handling pagination
-----------------------------------------------------------------------------------------------------------------

There are several methods, such as `EmailLists`, `Subscribers` and `Campaigns`, that return paginated results. To get the next page call `Next(ctx)` on a result. If there are no more results, it returns `nil`.

```
page, err := client.Subscribers(ctx, "list-uuid", mailcoach.ListOptions{})
if err != nil {
    return err
}
for page != nil {
    for _, subscriber := range page.Data {
        fmt.Println(subscriber.Email)
    }
    page, err = page.Next(ctx)
    if err != nil {
        return err
    }
}
```

`Previous(ctx)` works the same way. `Page` exposes `Data`, `Links` and `Meta`. Server links retain their filters and ordering. Absolute, root-relative and API-relative links are supported, but links outside the configured API origin or path are rejected before credentials are sent.

Use `ListOptions` for pagination, filtering and sorting:

```
options := mailcoach.ListOptions{
    Page: 2,
    PerPage: 25,
    Sort: "-sent",
    Filters: map[string]string{"status": "sent"},
}
page, err := client.Campaigns(ctx, options)
```

Leave options at zero values to use server defaults. Allowed filters and sorts depend on the endpoint and Mailcoach version. Filter names use `filter[name]` and are URL-encoded once.

Working with email lists
--------------------------------------------------------------------------------------------------------------------------------

Here's how to get all email lists:

```
lists, err := client.EmailLists(ctx, mailcoach.ListOptions{})
```

You can also get a single email list:

```
list, err := client.EmailList(ctx, "list-uuid")
```

This is how you can create an email list:

```
list, err := client.CreateEmailList(ctx, mailcoach.Attributes{
    "name": "My new list",
    "default_from_email": "john@example.com",
})
```

Read properties such as `list.Name` and `list.RequiresConfirmation`. To update a list, pass only the attributes you want to change:

```
list, err = client.UpdateEmailList(ctx, list.UUID, mailcoach.Attributes{"name": "A new name"})
```

`DeleteEmailList(ctx, list.UUID)` deletes the list. `AddTagToEmailList(ctx, list.UUID, attributes)`, `UpdateTagOnEmailList(ctx, list.UUID, tagUUID, attributes)` and `DeleteTagFromEmailList(ctx, list.UUID, tagUUID)` manage list tags. `UnsubscribeEmail(ctx, list.UUID, email)` unsubscribes an address directly.

Working with subscribers
--------------------------------------------------------------------------------------------------------------------------------

Here is how to create a subscriber:

```
subscriber, err := client.CreateSubscriber(ctx, "list-uuid", mailcoach.Attributes{
    "email": "john@example.com",
    "first_name": "John",
    "last_name": "Doe",
    "tags": []string{"customer"},
    "extra_attributes": map[string]any{"plan": "trial"},
})
```

Creation follows Mailcoach's confirmation behavior. Supply `skip_confirmation` or `strict` only when you intend to override server defaults. Explicit `false` values are sent unchanged.

`Subscribers(ctx, listUUID, options)` returns a page. `Subscriber(ctx, uuid)` retrieves a subscriber directly. `FindByEmail(ctx, listUUID, email)` returns a subscriber pointer or `nil` for an empty successful result. It preserves plus signs and other query characters. Authentication and connection failures remain errors, not missing subscribers.

You can get properties such as `subscriber.Email`, `subscriber.Tags` and `subscriber.ExtraAttributes`. `IsSubscribed()` is true only when `SubscribedAt` is non-nil and `UnsubscribedAt` is nil. `IsUnconfirmed()` is true when both are nil.

```
subscriber, err = client.UpdateSubscriber(ctx, subscriber.UUID, mailcoach.Attributes{"first_name": "Jane"})
```

Subscriber updates use PATCH. Other updates use PUT. Use `DeleteSubscriber`, `ConfirmSubscriber`, `ResendConfirmation`, `UnsubscribeSubscriber` and `ResubscribeSubscriber` with the subscriber UUID. `AddSubscriberTags(ctx, uuid, tags)` preserves existing tags. `RemoveSubscriberTags(ctx, uuid, tags)` removes only those tags. These low-level methods do not implicitly create subscribers.

Working with models
-----------------------------------------------------------------------------------------------------------------

The PHP package's Eloquent trait becomes an explicit helper around your own Go model. Implement `SubscriberModel` to choose its email, list and creation attributes:

```
func (u *User) MailcoachEmail() string {
    return u.ContactEmail
}

func (u *User) MailcoachEmailListUUID() string {
    return u.NewsletterListUUID
}

func (u *User) MailcoachAttributes() mailcoach.Attributes {
    return mailcoach.Attributes{
        "first_name": u.FirstName,
        "extra_attributes": map[string]any{"plan": u.Plan},
    }
}
```

Return `nil` from `MailcoachAttributes` to send no attributes besides email. The model can be a Laravel model or any application struct. No database columns are required.

```
subscription := client.ForModel(user)
if err := subscription.Subscribe(ctx, nil); err != nil {
    return err
}
return subscription.Tag(ctx, []string{"customer"})
```

`Subscribe` creates a subscriber if missing. Existing subscribers are left unchanged, including their attributes and subscription status. `Resubscribe` explicitly resubscribes an unsubscribed subscriber, creates one if missing, and leaves active or unconfirmed subscribers unchanged.

`Tag` creates a subscriber if missing, then adds the tags. It preserves existing tags and subscription status. `Unsubscribe` and `Untag` do nothing if the subscriber is missing. Empty tag slices do nothing, including skipping lookup.

Every helper operation accepts one optional trailing list UUID to override the model's list:

```
err := subscription.Subscribe(ctx, mailcoach.Attributes{"first_name": "Jane"}, "other-list-uuid")
```

An override applies only to that call. Subsequent calls use the model's list unless you pass another override. Explicit attributes replace matching values from `MailcoachAttributes`. The email always comes from `MailcoachEmail`, even if attributes contain an `email` key. Model attributes are not mutated.

`subscription.Subscriber(ctx)` returns the SDK subscriber or `nil`. `subscription.IsSubscribed(ctx)` returns false for missing, unconfirmed or unsubscribed subscribers. Both can return API errors.

All operations run synchronously and can make API requests, including lookup and status methods. Results are not cached. Blank email addresses or list UUIDs cause an error before a request is sent. Models are read on every operation. Changing a model's email does not update the old Mailcoach subscriber's address. The helper installs no listeners and does not sync changes automatically.

Working with campaigns
--------------------------------------------------------------------------------------------------------------------------

Here's how to get all campaigns or a single campaign:

```
campaigns, err := client.Campaigns(ctx, mailcoach.ListOptions{})
campaign, err := client.Campaign(ctx, "campaign-uuid")
```

This is how you can create a campaign:

```
campaign, err := client.CreateCampaign(ctx, mailcoach.Attributes{
    "name": "My new campaign",
    "subject": "Here is some fantastic content for you",
    "email_list_uuid": "list-uuid",
    "template_uuid": "template-uuid",
    "fields": map[string]any{
        "title": "Content for the title placeholder",
        "content": "# My title",
    },
})
```

The template is optional. Use `html` to supply HTML directly. When using the Markdown editor, Mailcoach handles Markdown supplied in template fields.

Read properties such as `campaign.Name`, `campaign.Subject`, `campaign.Status` and `campaign.WebviewHTML`. To save changes, call `UpdateCampaign(ctx, campaign.UUID, attributes)`.

A test mail is sent with `SendTest(ctx, campaign.UUID, "john@example.com")`. To send to multiple people, pass several addresses. The SDK sends them as one comma-separated string, as Mailcoach expects.

The campaign is sent to its audience only when you call `Send(ctx, campaign.UUID)`. `DeleteCampaign(ctx, campaign.UUID)` deletes it. `CampaignOpens`, `CampaignClicks`, `CampaignBounces` and `CampaignUnsubscribes` each take a campaign UUID and list options, returning typed report pages.

Working with automations
--------------------------------------------------------------------------------------------------------------------------------

`TriggerAutomation(ctx, automationUUID, subscriberUUIDs)` triggers an automation for the selected subscribers. Manage its mails with `AutomationMails(ctx, options)`, `AutomationMail(ctx, uuid)`, `CreateAutomationMail(ctx, attributes)`, `UpdateAutomationMail(ctx, uuid, attributes)` and `DeleteAutomationMail(ctx, uuid)`.

Working with templates
--------------------------------------------------------------------------------------------------------------------------

Use `Templates(ctx, options)`, `Template(ctx, uuid)`, `CreateTemplate(ctx, attributes)`, `UpdateTemplate(ctx, uuid, attributes)` and `DeleteTemplate(ctx, uuid)`.

Working with transactional mails
--------------------------------------------------------------------------------------------------------------------------------------------------------

`TransactionalMails(ctx, options)` and `TransactionalMail(ctx, uuid)` retrieve sent messages. `TransactionalMailTemplates(ctx, options)` and `TransactionalMailTemplate(ctx, uuid)` retrieve named templates.

```
err := client.SendTransactionMail(ctx, mailcoach.Attributes{
    "mail_name": "receipt",
    "from": "sender@example.com",
    "to": "reader@example.com",
    "replacements": map[string]string{"name": "Reader"},
    "attachments": []map[string]any{{
        "name": "receipt.txt",
        "content": "aGVsbG8=",
        "content_type": "text/plain",
        "content_id": nil,
    }},
    "store": false,
})
```

Supply attachment content as base64. Optional fields include `subject`, `cc`, `bcc`, `reply_to` and `fake`. The SDK does not queue messages locally or retry sends.

Custom endpoints and resources
--------------------------------------------------------------------------------------------------------------------------------------------------

`Request(ctx, method, uri, payload, result)` exposes endpoints not covered by a typed method. Use API-relative URIs such as `templates?filter[name]=receipt`. Pass a result pointer for JSON decoding or `nil` to ignore the successful body. `RequestBytes` returns raw bytes for empty or non-JSON responses. Absolute URLs must remain inside the configured API origin and path, even for writes.

Create and update methods accept `mailcoach.Attributes` or any JSON-serializable application struct. Use JSON tags on custom structs. To decode a completely custom resource type, pass a custom envelope to `Request`. Resource structs retain unknown fields in `Extra` when serialized with `encoding/json/v2`. Timestamps retain server strings. Nullable fields use pointers. Recipient fields accept strings or arrays.

Handling failures
-----------------------------------------------------------------------------------------------------------

```
campaign, err := client.Campaign(ctx, "campaign-uuid")
if err != nil {
    var apiErr *mailcoach.APIError
    if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {
        return nil
    }
    return err
}
```

API errors retain `StatusCode`, `Message`, field validation `Errors`, original `Body` and `RetryAfter`. Inspect statuses 400, 401, 404, 422 and 429 for the PHP SDK's action-failed, unauthorized, not-found, invalid-data and rate-limited cases. Other non-2xx responses are API errors too. `RetryAfter` can be seconds or an HTTP date. Error strings omit response bodies, which can contain personal data. Do not log the full error struct indiscriminately.

Transport errors wrap their cause. Use `errors.Is(err, context.Canceled)` or `errors.Is(err, context.DeadlineExceeded)` for cancellation and timeouts. Invalid successful JSON is an error rather than an empty record. Configuration failures expose `ErrMissingToken`, `ErrInvalidToken`, `ErrInvalidEndpoint` and `ErrInvalidTimeout`. Unsafe links return `ErrUnsafeURL` and invalid identifiers return `ErrInvalidIdentifier`.

Requests default to a 30-second total timeout, never follow redirects and do not automatically retry rejected requests. If a write times out, its server-side outcome may be unknown. Do not retry creation or sending blindly.

Differences from PHP
--------------------------------------------------------------------------------------------------------------------

The PHP repositories have README-based guides rather than a `docs` tree. This guide preserves their usage headings and wording, with additional sections for all SDK endpoints.

Resources are data structs rather than active records. Replace `save`, `delete` and resource action methods with explicit client operations using the resource UUID. Partial attribute objects avoid sending read-only server fields. Payloads use JSON instead of PHP's form-parameter encoding. This preserves explicit false, null and nested values. Application models implement `SubscriberModel` rather than inheriting a trait. There is no facade or global fake. Laravel's HTTP fake and standard Go transports provide isolated testing.

The port was checked against `spatie/laravel-mailcoach-sdk` at `dc7005c`, its SDK dependency `spatie/mailcoach-sdk-php` at `ff49312`, and `spatie/laravel-mailcoach-sdk-rust` at `20f0e29`. The Rust port supplied transport and pagination lessons. PHP defines the model-helper behavior, including extension points absent from the Rust port.

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
