spatie / laravel-mailcoach-sdk
An SDK to easily work with the Mailcoach API in Laravel apps
Requires
- php: ^8.3
- guzzlehttp/guzzle: ^7.5
- illuminate/contracts: ^12.0|^13.0
- spatie/laravel-package-tools: ^1.13.0
- spatie/mailcoach-sdk-php: ^1.0
Requires (Dev)
- laravel/pint: ^1.0
- nunomaduro/collision: ^8.0|^9.0
- orchestra/testbench: ^10.0|^11.0
- pestphp/pest: ^4.0
- pestphp/pest-plugin-laravel: ^4.0
- spatie/laravel-ray: ^1.26
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
This package contains the PHP SDK to work with Mailcoach. Both self-hosted (v6 and up) and hosted Mailcoach (aka Mailcoach Cloud) are supported. Using this package you can manage email lists, subscribers and campaigns.
Here are a few examples:
use Spatie\MailcoachSdk\Facades\Mailcoach; // creating a campaign $campaign = Mailcoach::createCampaign([ 'email_list_uuid' => 'use-a-real-email-list-uuid-here', 'name' => 'My new campaign', 'fields' => [ 'title' => 'The title on top of the newsletter', 'content' => '# Welcome to my newsletter', ], ]); // sending a test of the campaign to the given email address $campaign->sendTest('john@example.com'); // sending a campaign $campaign->send();
By default, Mailcoach' endpoints will are paginated with a limit of 1000. The package makes it easy to work with paginated resources. Just call ->next() to get the next page.
// listing all subscribers of a list $subscribers = $mailcoach->emailList('use-a-real-email-list-uuid-here')->subscribers(); do { foreach($subscribers as $subscriber) { echo $subscriber->email; } } while($subscribers = $subscribers->next())
Support us
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
Installation
You can install the package via composer:
composer require spatie/laravel-mailcoach-sdk
You must publish the config file with:
php artisan vendor:publish --tag="mailcoach-sdk-config"
This is the contents of the published config file:
return [ /* * You'll find both the API token and endpoint on Mailcoach' * API tokens screen in the Mailcoach settings. */ 'api_token' => env('MAILCOACH_API_TOKEN'), 'endpoint' => env('MAILCOACH_API_ENDPOINT'), ];
In your .env file you should add the entries from the config file mentioned above. You'll find both the API token and endpoint on Mailcoach' API tokens screen in the Mailcoach settings.
Usage
You can use the Spatie\MailcoachSdk\Facades\Mailcoach facade to perform most operations.
Handling pagination
There are several methods, such as emailLists(), 'subscribers()' and campaigns() to will return paginated results. To get the next page of results just call next() on a result. If there are no more results, that method returns null.
Here's how you display the email addresses of every subscriber on a list
use Spatie\MailcoachSdk\Facades\Mailcoach; $subscribers = Mailcoach::subscribers('<email-list-uuid'); do { foreach($subscribers as $subscriber) { echo $subscriber->email; } } while($subscribers = $subscribers->next())
On paginated results, $subscribers in the example above there are also some more convenience methods:
results(): get the results. A results object is also iterable, so you can also get to the results by simply using the object in a loopnext(): fetch the next page of resultsprevious(): fetch the previous page of resultscurrentPage(): get the current page numbertotal(): get the total number of results across all pagesnextUrl(): get the URL that will be called to get the next page of resultspreviousUrl(): get the URL that will be called to get the previous page of results
Working with email lists
Here's how to get all email lists:
use Spatie\MailcoachSdk\Facades\Mailcoach; $emailLists = Mailcoach::emailLists();
You can get a single email list:
$emailList = $this->mailcoach->emailList('<uuid-of-email-list>');
This is how you can create an email list:
use Spatie\MailcoachSdk\Facades\Mailcoach; Mailcoach::createEmailList(['name' => 'My new email list']);
You can get properties of email list:
$emailList->name; $emailList->uuid; // ...
Take a look at the source code of Spatie\MailcoachSdk\Resources\EmailList to see the list of available properties.
You can update an email list by change one of the properties and calling save().
$emailList->name = 'Updated name'; $emailList->save();
You can delete an email list by calling delete().
$emailList->delete();
Working with subscribers
To get all subscribers of a list, you can call subscribers() on an email list.
use Spatie\MailcoachSdk\Facades\Mailcoach; $subscribers = Mailcoach::emailList('<uuid-of-email-list>')->subscribers();
Optionally, you can pass filters to subscribers(). Here how to get all subscribers with a Gmail-address.
use Spatie\MailcoachSdk\Facades\Mailcoach; $subscribers = Mailcoach::emailList('<uuid-of-email-list>') ->subscribers(['filter[email]=gmail.com']);
Alternatively, you can call subscribers() on $mailcoach
use Spatie\MailcoachSdk\Facades\Mailcoach; $subscribers = Mailcoach::subscribers('<uuid-of-email-list>', $optionalFilters);
There's also a convenience method to quickly get a subscriber from a list.
// returns instance of Spatie\MailcoachSdk\Resources\Subscriber // or null if the subscriber does not exist. $subscriber = $emaillist->subscriber('john@example.com');
Alternatively, you can get a subscriber by its UUID:
$subscriber = $mailcoach->subscriber('<subscriber-uuid>');
This how you can create a subscriber:
use Spatie\MailcoachSdk\Facades\Mailcoach; $subscriber = Mailcoach::createSubscriber( emailListUuid: '<email-list-uuid>', attributes: [ 'email' => '<email-address>', 'first_name' => 'John', 'last_name' => 'Doe', 'tags' => ['Newsletter'], ]);
You can get properties of a subscriber:
$subscriber->firstName; $subscriber->email; // ...
Take a look at the source code of Spatie\MailcoachSdk\Resources\Subscriber to see the list of available properties.
You can update a subscriber by change one of the properties and calling save().
$subscriber->firstName = 'Updated name'; $subscriber->save();
You can confirm, unsubscribe and delete a subscriber by calling these methods.
$subscriber->confirm(); $subscriber->unsubscribe(); $subscriber->delete();
Working with Eloquent models
Add the InteractsWithMailcoach trait and implement MailcoachSubscriber on your model, typically your User model. The trait assumes the model has an email property. The required mailcoachEmailListUuid() method determines which list the model uses.
use Illuminate\Foundation\Auth\User as Authenticatable; use Spatie\MailcoachSdk\Concerns\InteractsWithMailcoach; use Spatie\MailcoachSdk\Contracts\MailcoachSubscriber; class User extends Authenticatable implements MailcoachSubscriber { use InteractsWithMailcoach; public function mailcoachEmailListUuid(): string { return '<email-list-uuid>'; } }
You can then call:
$user->subscribeToMailcoach(); $user->tagMailcoach(['activated', 'subscribed']); $user->untagMailcoach(['trial']); $user->unsubscribeFromMailcoach(); $user->resubscribeToMailcoach();
Tag methods accept arrays, matching the PHP SDK's addTags() and removeTags() methods. These operations return the model, so you can chain them:
$user->subscribeToMailcoach()->tagMailcoach(['activated']);
subscribeToMailcoach() creates a subscriber if missing. Existing subscribers are left unchanged, including their attributes and subscription status. Use resubscribeToMailcoach() to explicitly resubscribe an unsubscribed subscriber. It creates a subscriber if missing and leaves active or unconfirmed subscribers unchanged.
tagMailcoach() creates a subscriber if missing, then adds the given tags. It preserves existing tags and subscription status. unsubscribeFromMailcoach() and untagMailcoach() do nothing if the subscriber is missing. Empty tag arrays do nothing.
Every operation accepts an optional trailing emailListUuid argument to override the model's list:
$user->subscribeToMailcoach(emailListUuid: $otherListUuid); $user->tagMailcoach(['customer'], emailListUuid: $otherListUuid); $user->isSubscribedToMailcoach(emailListUuid: $otherListUuid);
An override applies only to that call. Each subsequent call, including a chained call, uses the model's list unless you pass another override.
To customize the email address or subscriber creation attributes, override these methods on your model:
public function mailcoachEmail(): string { return $this->contact_email; } public function mailcoachAttributes(): array { return [ 'first_name' => $this->first_name, 'last_name' => $this->last_name, 'extra_attributes' => ['plan' => $this->plan], ]; }
By default, no attributes besides email are sent. You can also pass creation attributes to subscribeToMailcoach():
$user->subscribeToMailcoach(['first_name' => 'Jane', 'tags' => ['customer']]);
Explicit attributes replace matching values from mailcoachAttributes(). The email always comes from mailcoachEmail(), even if attributes contain an email key. Creation follows Mailcoach's confirmation behavior unless you supply an option such as skip_confirmation.
To check subscription status or access the SDK subscriber:
$isSubscribed = $user->isSubscribedToMailcoach(); $subscriber = $user->mailcoachSubscriber(); $subscriber?->confirm();
mailcoachSubscriber() returns a Spatie\MailcoachSdk\Resources\Subscriber or null. isSubscribedToMailcoach() returns false for missing, unconfirmed, or unsubscribed subscribers.
All operations run synchronously and can make API requests, including lookup and status methods. Results are not cached. SDK errors are passed through to your application. Blank email addresses or list UUIDs cause an exception before a request is sent.
Adding the trait does not register model listeners or sync changes automatically. Subscribers are looked up using the current email and selected list. Changing the model's email does not update the old Mailcoach subscriber's address. No database columns are required.
Working with campaigns
Here's how to get all campaigns.
use Spatie\MailcoachSdk\Facades\Mailcoach; $campaigns = Mailcoach::campaigns();
You can also get a single campaign();
use Spatie\MailcoachSdk\Facades\Mailcoach; $campaign = Mailcoach::campaign('<campaign-uuid>');
This is how you can create a campaign:
use Spatie\MailcoachSdk\Facades\Mailcoach; $campaign = Mailcoach::createCampaign([ 'name' => 'My new campaign', 'subject' => 'Here is some fantastic content for you', 'email_list_uuid' => '<email-list-uuid>', // optionally, you can specify the uuid of a template 'template_uuid' => '<template-uuid>', // if that template has field, you can pass the values // in the `fields` array. If you use the markdown editor, // we'll automatically handle any passed markdown 'fields' => [ 'title' => 'Content for the title place holder', 'content' => '# My title', ], ]);
You can get properties of a campaign:
$campaign->name; $campaign->subject; // ...
Take a look at the source code of Spatie\MailcoachSdk\Resources\Campaign to see the list of available properties.
You can update a campaign by change one of the properties and calling save().
$campaign->name = 'Campaign'; $campaign->save();
A test mail will be sent when calling sendTest():
// sending a test to a single person $campaign->sendTest('john@example.com'); // sending a test to multiple persons $campaign->sendTest(['john@example.com', 'jane@example.com']);
The campaign will be sent to all subscribers of your list, by calling send():
$campaign->send();
A campaign can be deleted:
$campaign->delete();
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.