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

intonate/laravel-mandrill-driver

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require intonate/laravel-mandrill-driver
    

    For Laravel 11, use ^4.0; adjust version per your Laravel version.

  2. Publish Config (optional but recommended):

    php artisan vendor:publish --provider="Intonate\MandrillDriver\MandrillDriverServiceProvider" --tag="config"
    

    This generates config/mandrill.php with default settings.

  3. Configure .env:

    MAIL_MAILER=mandrill
    MANDRILL_SECRET=your_mandrill_api_key
    

    Optionally set MANDRILL_API_URL if using a custom Mandrill endpoint.

  4. First Use Case: Send an email via Laravel’s Mail facade (no additional setup needed):

    use Illuminate\Support\Facades\Mail;
    
    Mail::send([...], [...], function ($message) {
        $message->to('recipient@example.com')
                ->subject('Test Email');
    });
    

Key Files to Review

  • config/mandrill.php: API key, timeout, and retry settings.
  • config/mail.php: Ensure mandrill is listed under mailers.

Implementation Patterns

Core Workflows

1. Basic Email Sending

Leverage Laravel’s built-in Mail facade with the Mandrill driver:

Mail::to('user@example.com')
    ->subject('Welcome!')
    ->view('emails.welcome')
    ->send();

2. Attachments and Inline Images

Use Mandrill’s advanced features:

$message = new \Illuminate\Mail\Message();
$message->to('user@example.com')
        ->subject('With Attachments')
        ->attach('path/to/file.pdf')
        ->embedData($imageData, 'image.jpg')
        ->withSwiftMessage(function ($swiftMessage) {
            $swiftMessage->getChildren()
                         ->first()
                         ->getHeaders()
                         ->addTextHeader('X-MC-Tags', 'invoice');
        });

3. Templates and Variables

Mandrill templates require a custom approach:

Mail::send([], [], function ($message) {
    $message->to('user@example.com')
            ->subject('Template Email')
            ->withSwiftMessage(function ($swiftMessage) use ($templateData) {
                $swiftMessage->getChildren()
                             ->first()
                             ->setFrom(['address' => 'noreply@yourdomain.com', 'name' => 'Your App'])
                             ->setTemplateId('your_mandrill_template_id')
                             ->setTemplateContent([
                                 'name' => $templateData['name'],
                                 'url'  => $templateData['url'],
                             ]);
            });
});

4. Async Sending with Queues

Queue emails for background processing:

Mail::later(now()->addMinutes(10), $user, 'emails.welcome');

Integration Tips

Customizing Headers

Use SwiftMailer’s withSwiftMessage to add Mandrill-specific headers:

$message->withSwiftMessage(function ($swiftMessage) {
    $swiftMessage->getHeaders()
                 ->addTextHeader('X-MC-Tags', 'newsletter,promo');
});

Logging and Debugging

Enable Mandrill’s logging via config:

'mandrill' => [
    'log' => [
        'enabled' => true,
        'channel' => 'single',
    ],
],

Testing

Use Laravel’s MailFake for unit tests:

$mailer = $this->app->make('mailer');
$mailer->pretend(true);
Mail::send([...], [...], function ($message) { /* ... */ });
$this->assertCount(1, Mail::failures());

Gotchas and Tips

Pitfalls

1. API Key Exposure

  • Risk: Hardcoding MANDRILL_SECRET in .env is fine, but avoid committing .env to version control.
  • Fix: Use Laravel’s .env.example and add .env to .gitignore.

2. Template ID Misconfiguration

  • Issue: Mandrill templates require a template_id and structured content. Passing raw views without conversion may fail.
  • Fix: Use setTemplateId() and setTemplateContent() as shown in the workflows above.

3. Rate Limits and Timeouts

  • Problem: Mandrill has API rate limits (e.g., 10 requests/sec). Default timeout (30s) may be too short for slow connections.
  • Solution: Adjust in config/mandrill.php:
    'timeout' => 60,
    'retries' => 3,
    

4. SwiftMailer Overrides

  • Gotcha: Custom SwiftMailer plugins may conflict with the driver’s built-in Mandrill transport.
  • Workaround: Disable conflicting plugins or extend the driver’s transport class.

Debugging

Enable Verbose Logging

Add to config/mandrill.php:

'log' => [
    'enabled' => true,
    'channel' => 'stack', // or 'single'
    'level' => 'debug',
],

Check HTTP Responses

Inspect the mandrill.log file (or configured channel) for:

  • 429 Too Many Requests: Increase retries or throttle sending.
  • 401 Unauthorized: Verify MANDRILL_SECRET.
  • 400 Bad Request: Validate template IDs and content structure.

Extension Points

Custom Transport Logic

Extend the Mandrill transport for custom behavior:

namespace App\Mail\Transport;

use Intonate\MandrillDriver\Transport\MandrillTransport;

class CustomMandrillTransport extends MandrillTransport
{
    public function sendSwiftMessage(Swift_Message $message)
    {
        // Add custom logic (e.g., modify headers before sending)
        $this->addCustomHeader($message);
        parent::sendSwiftMessage($message);
    }

    protected function addCustomHeader(Swift_Message $message)
    {
        $message->getHeaders()
                ->addTextHeader('X-Custom-Header', 'value');
    }
}

Register the custom transport in AppServiceProvider:

public function boot()
{
    $this->app->bind(
        \Illuminate\Contracts\Mail\Transport::class,
        function () {
            return new \App\Mail\Transport\CustomMandrillTransport(
                config('mail.mailers.mandrill.transport'),
                config('services.mandrill')
            );
        }
    );
}

Webhook Integration

Use Mandrill’s webhooks (e.g., for tracking opens/clicks) by:

  1. Configuring webhooks in the Mandrill dashboard.
  2. Handling callbacks in Laravel:
    Route::post('/mandrill/webhook', [MandrillWebhookController::class, 'handle']);
    

Fallback to SMTP

Configure a fallback mailer in config/mail.php:

'default' => env('MAIL_MAILER', 'mandrill'),
'mailers' => [
    'mandrill' => [
        'transport' => 'mandrill',
    ],
    'smtp' => [
        'transport' => 'smtp',
        'host' => env('MAIL_HOST'),
        // ... other SMTP config
    ],
],

Then dynamically switch:

$mailer = app()->make('mailer');
$mailer->mailer('smtp'); // Fallback to SMTP if Mandrill fails
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.
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
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours