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

Laravel Mailcoach Mailer Laravel Package

spatie/laravel-mailcoach-mailer

Laravel mail driver to send transactional Mailables and Notifications via Mailcoach. Keeps an archive of sent emails, optionally tracks opens/clicks, supports resending from the UI, and lets you use Mailcoach templates with placeholder replacements.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-mailcoach-mailer
    

    Publish the config file:

    php artisan vendor:publish --provider="Spatie\MailcoachMailer\MailcoachMailerServiceProvider"
    
  2. Configure .env: Add Mailcoach API credentials:

    MAILCOACH_API_KEY=your_api_key_here
    MAILCOACH_API_URL=https://your-mailcoach-instance.app/api
    
  3. Set Mailer Driver: In config/mail.php, update the default driver to mailcoach:

    'default' => env('MAIL_MAILER', 'mailcoach'),
    
  4. First Use Case: Send a transactional email via Mailcoach:

    Mail::to('user@example.com')->send(new OrderShippedMail());
    

    Verify the email appears in the Mailcoach UI under Transactional Emails.


Where to Look First

  • README: Quick setup and basic usage.
  • Config File: Customize API URL, timeout, and logging.
  • Mailcoach Docs: Understand transactional email features (e.g., templates, analytics).

Implementation Patterns

Core Workflows

  1. Sending Emails: Use Laravel’s Mail facade as usual. The package intercepts and routes emails to Mailcoach.

    Mail::to($user->email)
        ->subject('Your Order Confirmation')
        ->send(new OrderConfirmationMail($order));
    
  2. Using Mailcoach Templates: Replace dynamic content in Mailcoach templates with Laravel variables:

    Mail::to($user->email)
        ->mailcoachTemplate('order_confirmation')
        ->with([
            'order_id' => $order->id,
            'total' => $order->total,
        ])
        ->send();
    

    Note: Templates must be pre-created in Mailcoach’s Templates section.

  3. Resending Emails: Leverage Mailcoach’s UI to resend transactional emails (e.g., for failed deliveries). No code changes needed.

  4. Tracking Opens/Clicks: Enable tracking in Mailcoach’s Settings > Transactional Emails. Data appears in the Analytics tab.


Integration Tips

  • Queue Emails: Use Laravel queues to avoid blocking requests:

    Mail::to($user->email)->queue(new WelcomeMail());
    
  • Fallback to Default Mailer: Configure a fallback in config/mailcoach.php:

    'fallback' => env('MAIL_MAILER_FALLBACK', 'smtp'),
    

    Emails will retry via the fallback if Mailcoach fails.

  • Logging: Enable debug logging in config/mailcoach.php:

    'log' => env('MAILCOACH_LOG', true),
    

    Check storage/logs/laravel.log for API errors.

  • Testing: Use Mailcoach’s sandbox mode (if available) or mock the mailer in tests:

    $this->mailer->shouldReceive('sendUsingMailcoach')->once();
    

Gotchas and Tips

Pitfalls

  1. API Key Permissions: Ensure the Mailcoach API key has Transactional Emails permissions. Test with a dedicated key during development.

  2. Template Mismatches: If using templates, verify:

    • The template name matches exactly (case-sensitive).
    • All required variables are passed via with().
    • Placeholders in the template match the variable names.
  3. Rate Limits: Mailcoach may throttle requests. Monitor the storage/logs/laravel.log for 429 Too Many Requests errors. Adjust the timeout in config/mailcoach.php if needed.

  4. Async Processing: Mailcoach processes emails asynchronously. Avoid polling for delivery status in real-time. Use webhooks (if supported) or Mailcoach’s UI for tracking.


Debugging

  • API Errors: Enable MAILCOACH_LOG=true and check logs for Guzzle exceptions. Common issues:

    • Invalid API key (401 Unauthorized).
    • Missing template (404 Not Found).
    • Payload validation errors (422 Unprocessable Entity).
  • Payload Inspection: Temporarily log the raw payload sent to Mailcoach:

    \Spatie\MailcoachMailer\MailcoachMailer::macro('logPayload', function ($mailable) {
        \Log::debug('Mailcoach Payload:', [
            'to' => $mailable->to->address,
            'template' => $mailable->mailcoachTemplate ?? null,
            'data' => $mailable->mailcoachData ?? null,
        ]);
    });
    

Extension Points

  1. Custom Headers: Add headers to emails via the mailcoachHeaders method:

    Mail::to($user->email)
        ->mailcoachHeaders(['X-Custom-Header' => 'value'])
        ->send(new Mailable());
    
  2. Event Hooks: Listen for mailcoach.sent events to trigger side effects:

    event(new MailcoachSent($mailable, $response));
    

    Register the listener in EventServiceProvider:

    protected $listen = [
        'mailcoach.sent' => [
            \App\Listeners\LogMailcoachSend::class,
        ],
    ];
    
  3. Override Mailer: Extend the mailer class to add custom logic:

    namespace App\Mailcoach;
    
    use Spatie\MailcoachMailer\MailcoachMailer as BaseMailer;
    
    class Mailer extends BaseMailer {
        public function sendUsingMailcoach($mailable, array $failures = []) {
            // Custom logic here
            parent::sendUsingMailcoach($mailable, $failures);
        }
    }
    

    Bind it in AppServiceProvider:

    $this->app->bind(\Spatie\MailcoachMailer\MailcoachMailer::class, App\Mailcoach\Mailer::class);
    

Config Quirks

  • API URL: Use the full URL (e.g., https://your-subdomain.mailcoach.app/api). Avoid trailing slashes.

  • Timeout: Default is 10 seconds. Increase for slow connections:

    'timeout' => env('MAILCOACH_TIMEOUT', 30),
    
  • SSL Verification: Disable only if using a self-signed certificate (not recommended for production):

    'verify_ssl' => env('MAILCOACH_VERIFY_SSL', true),
    
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