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 Laravel Package

spatie/mailcoach

Self-hosted email marketing for Laravel: manage audiences, send campaigns with segmentation and A/B testing, track analytics, build automation workflows, and handle transactional emails—all in one Mailcoach app integrated with your project.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Email

  1. Installation

    composer require spatie/mailcoach
    php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-migrations"
    php artisan migrate
    php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-config"
    php artisan vendor:publish --provider="Spatie\Mailcoach\MailcoachServiceProvider" --tag="mailcoach-assets"
    
  2. Configure Mail Driver Update .env to use mailcoach as your default mail driver:

    MAIL_MAILER=mailcoach
    
  3. Create a Campaign

    php artisan mailcoach:campaign
    

    Follow prompts to define subject, body, and recipient list.

  4. Send Test Email

    use Spatie\Mailcoach\Facades\Mailcoach;
    
    Mailcoach::send('campaign-name', ['user@example.com']);
    

Where to Look First

  • Documentation: mailcoach.app/self-hosted (official docs)
  • Migrations: database/migrations/ for schema changes
  • Config: config/mailcoach.php for customization
  • Blade Templates: resources/views/vendor/mailcoach/ for UI overrides

Implementation Patterns

Core Workflows

1. Marketing Campaigns

  • Create/Edit Campaigns: Use the mailcoach:campaign Artisan command or the built-in UI to design campaigns with:

    • Drag-and-drop email builders
    • A/B testing (subject lines, content)
    • Segmentation (tags, custom fields)
    // Programmatically create a campaign
    $campaign = \Spatie\Mailcoach\Models\Campaign::create([
        'name' => 'Welcome Series',
        'subject' => 'Welcome to our platform!',
        'body' => '<h1>Hello!</h1><p>Thanks for joining.</p>',
    ]);
    
  • Schedule & Send:

    $campaign->schedule->update(['sent_at' => now()->addHours(1)]);
    $campaign->send();
    

2. Automations (Workflows)

  • Trigger-Based Emails: Use events to trigger workflows (e.g., user signup, order completion).

    // In EventServiceProvider
    protected $listen = [
        'user.registered' => ['Spatie\Mailcoach\Listeners\TriggerWorkflow', 'handle'],
    ];
    
    • Define workflows in the UI under Automations.
    • Use tags to segment contacts dynamically:
      $user->tags()->sync(['vip', 'new-2023']);
      
  • Delayed Actions:

    // Delay a workflow step by 3 days
    $workflowStep->delay = 3 * 24 * 60; // in minutes
    $workflowStep->save();
    

3. Transactional Emails

  • Override Default Mailer:

    // In a controller
    Mail::to('user@example.com')
        ->mailcoach('emails.welcome')
        ->send();
    
    • Templates live in resources/views/vendor/mailcoach/emails/.
  • Track Opens/Click: Automatically logs analytics via mailcoach:track-opens and mailcoach:track-clicks middleware.

4. Contact Management

  • Sync Contacts:

    // Add a contact
    $contact = \Spatie\Mailcoach\Models\Contact::create([
        'email' => 'user@example.com',
        'name' => 'John Doe',
        'custom_fields' => ['plan' => 'premium'],
    ]);
    
    // Bulk import via CSV
    php artisan mailcoach:import-contacts path/to/file.csv
    
  • Segmentation: Use tags or custom fields for filtering:

    $contacts = \Spatie\Mailcoach\Models\Contact::whereHas('tags', function($q) {
        $q->where('name', 'active-users');
    })->get();
    

Integration Tips

  • Laravel Events: Listen for Mailcoach\Events\CampaignSent or Mailcoach\Events\ContactSubscribed to extend functionality.

    event(new \Spatie\Mailcoach\Events\CampaignSent($campaign));
    
  • API Access: Use the built-in API for headless setups:

    $response = Http::post('http://your-app.test/api/mailcoach/campaigns', [
        'name' => 'API Campaign',
        'subject' => 'Hello via API',
        'body' => '<p>API-powered email</p>',
    ]);
    
  • Queue Workers: Run the queue worker for async processing:

    php artisan queue:work --queue=mailcoach
    

Gotchas and Tips

Pitfalls

  1. Mail Driver Misconfiguration:

    • Ensure MAIL_MAILER=mailcoach is set in .env. Forgetting this causes emails to fail silently.
    • Fix: Verify with php artisan config:get mail.mailer.
  2. Queue Stuck on "Processing":

    • If emails hang in the queue, check:
      • Database locks (mailcoach_schedules table).
      • Queue worker logs (storage/logs/laravel.log).
    • Fix: Restart the queue worker or manually retry:
      php artisan mailcoach:retry-failed
      
  3. Tracking Pixel Blocking:

    • Some email clients (e.g., Gmail) block tracking pixels by default.
    • Workaround: Use mailcoach:track-opens middleware with a fallback:
      if (!Mailcoach::isTrackingPixelBlocked()) {
          Mailcoach::trackOpen($email);
      }
      
  4. Custom Fields Not Syncing:

    • If custom fields don’t appear in the UI, ensure the custom_fields column is defined in the contacts table.
    • Fix: Re-run migrations or manually add the column:
      php artisan migrate:fresh --path=/vendor/spatie/mailcoach/database/migrations
      
  5. Memory Limits:

    • Bulk operations (e.g., mailcoach:import-contacts) may hit memory limits.
    • Fix: Increase memory_limit in php.ini or chunk imports:
      $chunkSize = 100;
      $contacts->chunk($chunkSize, function ($chunk) {
          // Process chunk
      });
      

Debugging

  • Log Emails: Enable debug mode in config/mailcoach.php:

    'debug' => env('MAILCOACH_DEBUG', false),
    

    Logs appear in storage/logs/mailcoach.log.

  • SQL Queries: Use Laravel Debugbar to inspect queries:

    composer require barryvdh/laravel-debugbar
    
  • Test Mode: Disable sending in config/mailcoach.php:

    'test_mode' => env('MAILCOACH_TEST_MODE', false),
    

    Emails are stored in the database but not sent.

Config Quirks

  1. Default From Address: Override in config/mailcoach.php:

    'from' => [
        'address' => 'noreply@yourdomain.com',
        'name' => 'Your Brand',
    ],
    
  2. Asset Paths: Customize asset paths if using a CDN:

    'assets' => [
        'path' => 'cdn/yourdomain.com/assets/mailcoach',
    ],
    
  3. Queue Connections: Specify a custom queue for Mailcoach:

    'queue' => 'mailcoach',
    

    Then configure the queue in .env:

    QUEUE_CONNECTION=database
    

Extension Points

  1. Custom Email Templates: Override default templates by publishing assets:

    php artisan vendor:publish --tag=mailcoach-assets
    

    Edit files in resources/views/vendor/mailcoach/.

  2. API Extensions: Add custom endpoints by extending the Spatie\Mailcoach\Http\Controllers namespace.

  3. Webhook Listeners: Trigger external actions via webhooks:

    // In config/mailcoach.php
    'webhooks' => [
        'campaign_sent' => 'https://your-app.com/webhooks/mailcoach',
    ],
    
  4. Custom Fields: Extend the contacts table schema:

    // In a migration
    Schema::table('mailcoach_contacts', function (Blueprint $table) {
        $table->string('custom_field')->nullable();
    });
    

    Update the UI via JavaScript hooks in resources/js/mailcoach.js.

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