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

Craft Mailcoach Laravel Package

spatie/craft-mailcoach

Mailcoach adapter plugin for Craft CMS 5+. Install via the Plugin Store or Composer to add Mailcoach integration to your Craft project. Requires PHP 8.2 or later.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/craft-mailcoach
    ./craft plugin/install mailcoach
    

    Verify installation via ./craft plugin/list (should show mailcoach as active).

  2. First Use Case:

    • Configure Mailcoach in Craft CMS Control Panel under Settings > Mailcoach.
    • Set up a Mailcoach Campaign (e.g., newsletter) and define a Mailcoach Template (e.g., welcome.html).
    • Use the mailcoach mailer in your code:
      use Spatie\CraftMailcoach\Facades\Mailcoach;
      
      Mailcoach::send('newsletter', ['user@example.com'], ['name' => 'John']);
      
  3. Key Files to Review:

    • config/mailcoach.php (default config, override in config/mailcoach.php).
    • vendor/spatie/craft-mailcoach/src/ (core logic, e.g., MailcoachService.php for advanced use).

Implementation Patterns

Core Workflows

  1. Sending Emails:

    • Basic Send:
      Mailcoach::send('campaign-slug', ['recipient@example.com'], ['data' => 'value']);
      
    • Batch Send:
      $recipients = ['a@example.com', 'b@example.com'];
      Mailcoach::send('campaign-slug', $recipients, ['key' => 'shared-value']);
      
    • With Attachments:
      Mailcoach::send('campaign-slug', ['email@example.com'], [], [
          'attachments' => [Storage::disk('public')->path('file.pdf')]
      ]);
      
  2. Dynamic Data Injection:

    • Use Twig variables in Mailcoach templates (e.g., {{ data.name }}).
    • Pass data via the 3rd argument:
      Mailcoach::send('campaign-slug', ['email@example.com'], [
          'name' => 'Alice',
          'custom_field' => 'value'
      ]);
      
  3. Event Listeners:

    • Listen for Mailcoach.Sent events to log or process sent emails:
      Event::on(
          \Spatie\CraftMailcoach\Events\MailcoachSent::class,
          \Spatie\CraftMailcoach\Events\MailcoachSent::class,
          function ($event) {
              // $event->mailcoachMessage contains sent data
          }
      );
      
  4. Integration with Craft CMS:

    • User-Specific Emails: Use Craft’s User model to fetch emails dynamically:
      $users = User::all();
      foreach ($users as $user) {
          Mailcoach::send('welcome', [$user->email], ['name' => $user->firstName]);
      }
      
    • Entry Triggers: Trigger emails on entry saves (e.g., after a form submission):
      Event::on(
          Entry::class,
          Entry::EVENT_AFTER_SAVE,
          function ($event) {
              if ($event->entry->type->handle === 'contact-form') {
                  Mailcoach::send('thank-you', [$event->entry->contactEmail], []);
              }
          }
      );
      
  5. Testing:

    • Use Mailcoach::fake() for unit tests:
      Mailcoach::fake();
      Mailcoach::send('test', ['email@example.com']);
      Mailcoach::assertSent('test', 1);
      

Gotchas and Tips

Pitfalls

  1. Template Paths:

    • Mailcoach templates must be placed in storage/craft-mailcoach/templates/ (not templates/).
    • Fix: Ensure templates exist in the correct directory or configure a custom path in config/mailcoach.php:
      'templatePath' => storage_path('app/mailcoach-templates'),
      
  2. Recipient Validation:

    • Mailcoach does not validate recipient emails by default. Invalid emails may cause silent failures.
    • Tip: Validate emails before sending:
      if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
          Mailcoach::send('campaign', [$email]);
      }
      
  3. Caching Issues:

    • Mailcoach caches compiled templates. Clear the cache after template updates:
      ./craft clear-caches
      
    • Debug: Disable caching in config/mailcoach.php for development:
      'cacheTemplates' => env('APP_ENV') !== 'local',
      
  4. PHP 8.2+ Requirements:

    • Error: Class 'Spatie\CraftMailcoach\...' not found if PHP < 8.2.
    • Fix: Upgrade PHP or check composer.json for version constraints.
  5. Rate Limiting:

    • Mailcoach may throttle sends if the Mailcoach API has rate limits.
    • Tip: Implement retries with exponential backoff:
      try {
          Mailcoach::send('campaign', [$email]);
      } catch (\Spatie\CraftMailcoach\Exceptions\MailcoachException $e) {
          // Retry logic here
      }
      

Debugging Tips

  1. Enable Logging: Add to config/mailcoach.php:

    'logSentMessages' => true,
    

    Check logs in storage/logs/craft-mailcoach.log.

  2. Inspect Sent Messages: Use the Mailcoach.Sent event to debug:

    Event::on(
        \Spatie\CraftMailcoach\Events\MailcoachSent::class,
        function ($event) {
            Craft::info('Sent to: ' . $event->mailcoachMessage->recipients[0]);
        }
    );
    
  3. Template Debugging:

    • Use Twig’s dump() in templates to inspect variables:
      {{ dump(data) }}
      
    • Tip: Enable Twig debugging in config/general.php:
      'devMode' => true,
      

Extension Points

  1. Custom Mailcoach Messages: Extend the MailcoachMessage class to add metadata:

    namespace App\Services;
    
    use Spatie\CraftMailcoach\MailcoachMessage;
    
    class CustomMailcoachMessage extends MailcoachMessage
    {
        public function __construct(string $campaign, array $recipients, array $data = [], array $options = [])
        {
            parent::__construct($campaign, $recipients, $data, $options);
            $this->customField = 'value';
        }
    }
    

    Use via:

    Mailcoach::send(new CustomMailcoachMessage('campaign', ['email@example.com']));
    
  2. Override Mailcoach Service: Bind a custom service in config/app.php:

    'services' => [
        \Spatie\CraftMailcoach\Facades\Mailcoach::class => \App\Services\CustomMailcoachService::class,
    ],
    
  3. Add Custom Fields to Templates: Extend the template context by modifying the MailcoachService:

    namespace App\Services;
    
    use Spatie\CraftMailcoach\MailcoachService;
    
    class CustomMailcoachService extends MailcoachService
    {
        protected function getTemplateData(): array
        {
            $data = parent::getTemplateData();
            $data['custom'] = 'value';
            return $data;
        }
    }
    
  4. Queue Mailcoach Jobs: Use Laravel’s queue system to defer sends:

    Mailcoach::queue('campaign', ['email@example.com']);
    

    Configure the queue in config/mailcoach.php:

    'queue' => 'mailcoach',
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport