Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mailcoach Sdk Php Laravel Package

spatie/mailcoach-sdk-php

PHP SDK for the Mailcoach API (self-hosted v6+ and Mailcoach Cloud). Manage email lists, subscribers, and campaigns: create and send campaigns, send tests, and browse paginated resources with an easy next() workflow.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/mailcoach-sdk-php guzzlehttp/guzzle
    
  2. Initialize Client:

    use Spatie\MailcoachSdk\Mailcoach;
    
    $mailcoach = new Mailcoach(
        env('MAILCOACH_API_KEY'),
        env('MAILCOACH_API_ENDPOINT') // e.g., 'https://your-mailcoach-instance.app/api'
    );
    
  3. First Use Case: Fetch and iterate through all email lists (paginated):

    $emailLists = $mailcoach->emailLists();
    
    foreach ($emailLists as $list) {
        echo $list->name;
    }
    
    // Handle pagination
    while ($emailLists->next()) {
        foreach ($emailLists as $list) {
            echo $list->name;
        }
    }
    

Key Starting Points

  • API Key & Endpoint: Retrieve from MailcoachSettingsAPI Tokens.
  • Core Resources: Focus on EmailList, Subscriber, Campaign, and Automation classes.
  • Pagination: Use next(), results(), and total() for large datasets.

Implementation Patterns

Workflow: Managing Subscribers

  1. Bulk Subscriber Management:

    // Add subscribers from a CSV
    $csv = collect(file('subscribers.csv'));
    foreach ($csv->skip(1) as $row) {
        $mailcoach->createSubscriber('list-uuid', [
            'email' => $row[0],
            'first_name' => $row[1],
        ]);
    }
    
  2. Tagging Logic:

    // Tag subscribers based on custom logic
    $subscribers = $mailcoach->emailList('list-uuid')->subscribers(['tag' => 'active']);
    foreach ($subscribers as $subscriber) {
        if ($subscriber->last_opened_at > now()->subDays(7)) {
            $subscriber->addTags(['engaged']);
        }
    }
    

Workflow: Campaign Automation

  1. Dynamic Campaign Creation:

    // Create a campaign with template fields
    $campaign = $mailcoach->createCampaign([
        'email_list_uuid' => 'list-uuid',
        'name' => 'Weekly Digest',
        'template_uuid' => 'template-uuid',
        'fields' => [
            'title' => 'Your Weekly Updates',
            'content' => '# Hello ' . $subscriber->first_name,
        ],
    ]);
    
  2. Scheduling with Laravel:

    // Schedule a campaign to send at a specific time
    $campaign->sendAt(\Carbon\Carbon::now()->addHours(2));
    

Integration with Laravel

  1. Service Provider Binding:

    // app/Providers/MailcoachServiceProvider.php
    public function register()
    {
        $this->app->singleton(Mailcoach::class, function ($app) {
            return new Mailcoach(
                config('mailcoach.api_key'),
                config('mailcoach.api_endpoint')
            );
        });
    }
    
  2. Event-Driven Workflows:

    // Trigger automation on user signup
    event(new UserRegistered($user));
    // In listener:
    $mailcoach->triggerAutomation('welcome-automation-uuid', [$subscriber->uuid]);
    

Pagination Handling

  1. Batch Processing:

    $subscribers = $mailcoach->emailList('list-uuid')->subscribers();
    while ($subscribers->next()) {
        foreach ($subscribers as $subscriber) {
            // Process in batches (e.g., 100 at a time)
            if ($subscriber->isDirty()) {
                $subscriber->save();
            }
        }
    }
    
  2. Cursor-Based Pagination (for large datasets):

    $cursor = null;
    do {
        $subscribers = $mailcoach->emailList('list-uuid')->subscribers(['cursor' => $cursor]);
        foreach ($subscribers as $subscriber) {
            // Process
        }
        $cursor = $subscribers->nextUrl(); // Update cursor
    } while ($cursor);
    

Gotchas and Tips

Common Pitfalls

  1. API Rate Limiting:

    • The SDK throws Spatie\MailcoachSdk\Exceptions\RateLimitedException.
    • Fix: Implement exponential backoff or retry logic:
      try {
          $campaign->send();
      } catch (RateLimitedException $e) {
          sleep($e->retryAfter);
          retry();
      }
      
  2. Pagination Edge Cases:

    • Always check next() returns null before looping:
      while ($subscribers = $subscribers->next()) { // Correct
          // ...
      }
      
    • Tip: Use total() to log progress for large datasets.
  3. Subscriber Email Quirks:

    • Emails with + (e.g., user+tag@example.com) may fail to fetch.
    • Fix: URL-encode the email in filters:
      $subscribers = $mailcoach->subscribers('list-uuid', ['email' => urlencode('user+tag@example.com')]);
      
  4. Campaign Fields:

    • Template fields must match the Mailcoach template exactly.
    • Tip: Fetch template fields first:
      $template = $mailcoach->template('template-uuid');
      dd($template->fields); // Inspect required fields
      

Debugging Tips

  1. Enable Guzzle Debugging:

    $mailcoach = new Mailcoach($apiKey, $endpoint, [
        'debug' => true,
        'handler' => GuzzleHttp\HandlerStack::create(new \GuzzleHttp\Handler\CurlHandler())
    ]);
    
  2. Log API Responses:

    $mailcoach->getHttpClient()->getEmitter()->attach(
        new \GuzzleHttp\Middleware::tap(function ($request, $response, $next) {
            \Log::debug('Mailcoach API Response', [
                'status' => $response->getStatusCode(),
                'body' => (string) $response->getBody(),
            ]);
        })
    );
    

Extension Points

  1. Custom HTTP Client: Override the default Guzzle client for middleware (e.g., auth, logging):

    $mailcoach = new Mailcoach($apiKey, $endpoint, [
        'http_client' => new \GuzzleHttp\Client([
            'headers' => ['X-Custom-Header' => 'value'],
        ]),
    ]);
    
  2. Resource Decorators: Extend resource classes (e.g., Subscriber) to add custom methods:

    class CustomSubscriber extends \Spatie\MailcoachSdk\Resources\Subscriber
    {
        public function isActive()
        {
            return $this->status === 'subscribed' && $this->unsubscribed_at === null;
        }
    }
    

    Note: Requires patching the SDK or using a decorator pattern.

  3. Webhook Handling: For automation triggers, validate subscriber UUIDs:

    $validUuids = $mailcoach->subscribers()->pluck('uuid');
    if (!collect($triggerData)->every(fn ($uuid) => in_array($uuid, $validUuids))) {
        throw new \InvalidArgumentException('Invalid subscriber UUIDs');
    }
    

Configuration Quirks

  1. Self-Hosted vs. Cloud:

    • Cloud endpoints use https://mailcoach.app/api.
    • Self-hosted: Ensure the endpoint includes /api (e.g., https://your-instance.com/api).
  2. Environment Variables:

    • Store API keys in .env:
      MAILCOACH_API_KEY=your_key_here
      MAILCOACH_API_ENDPOINT=https://your-instance.com/api
      
  3. Template UUIDs:

    • Templates are optional but required for dynamic content.
    • Tip: Fetch templates first:
      $templates = $mailcoach->templates();
      

Performance Tips

  1. Batch Operations:

    • Use chunk() for large subscriber updates:
      $subscribers->chunk(50)->each(function ($chunk) {
          foreach ($chunk as $subscriber) {
              $subscriber->addTags(['bulk-tag']);
              $subscriber->save();
          }
      });
      
  2. Lazy Loading:

    • Avoid eager-loading all subscribers at once:
      // Bad: Loads all 10,000 subscribers
      $allSubscribers = $mailcoach->emailList('list-uuid')->subscribers()->results();
      
      // Good: Process page-by-page
      $subscribers = $mailcoach->emailList('list-uuid')->subscribers();
      while ($subscribers->next()) {
          foreach ($subscribers as $subscriber) {
              // Process one page
          }
      }
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony