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.
Installation:
composer require spatie/laravel-mailcoach-mailer
Publish the config file:
php artisan vendor:publish --provider="Spatie\MailcoachMailer\MailcoachMailerServiceProvider"
Configure .env:
Add Mailcoach API credentials:
MAILCOACH_API_KEY=your_api_key_here
MAILCOACH_API_URL=https://your-mailcoach-instance.app/api
Set Mailer Driver:
In config/mail.php, update the default driver to mailcoach:
'default' => env('MAIL_MAILER', 'mailcoach'),
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.
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));
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.
Resending Emails: Leverage Mailcoach’s UI to resend transactional emails (e.g., for failed deliveries). No code changes needed.
Tracking Opens/Clicks: Enable tracking in Mailcoach’s Settings > Transactional Emails. Data appears in the Analytics tab.
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();
API Key Permissions: Ensure the Mailcoach API key has Transactional Emails permissions. Test with a dedicated key during development.
Template Mismatches: If using templates, verify:
with().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.
Async Processing: Mailcoach processes emails asynchronously. Avoid polling for delivery status in real-time. Use webhooks (if supported) or Mailcoach’s UI for tracking.
API Errors:
Enable MAILCOACH_LOG=true and check logs for Guzzle exceptions. Common issues:
401 Unauthorized).404 Not Found).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,
]);
});
Custom Headers:
Add headers to emails via the mailcoachHeaders method:
Mail::to($user->email)
->mailcoachHeaders(['X-Custom-Header' => 'value'])
->send(new Mailable());
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,
],
];
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);
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),
How can I help you explore Laravel packages today?