Installation:
composer require tolotra/mailgun
Publish the config file:
php artisan vendor:publish --provider="Tolotra\Mailgun\MailgunServiceProvider"
Configuration:
Edit .env with your Mailgun API key and domain:
MAILGUN_API_KEY=your_api_key
MAILGUN_DOMAIN=your_domain.mailgun.org
First Use Case: Send a basic email via Tinker or a controller:
use Tolotra\Mailgun\Facades\Mailgun;
Mailgun::send([
'from' => 'excited-user@example.com',
'to' => 'you@example.com',
'subject' => 'Hello',
'text' => 'Testing the Mailgun wrapper!'
]);
Tolotra\Mailgun\Facades\Mailgun (primary entry point).config/mailgun.php (adjust API endpoint, timeout, etc.).Mailgun::send([
'from' => 'sender@example.com',
'to' => 'recipient@example.com',
'subject' => 'Subject',
'text' => 'Plain text body',
]);
Mailgun::send([
'from' => 'sender@example.com',
'to' => 'recipient@example.com',
'subject' => 'Subject',
'html' => '<h1>HTML Content</h1>',
]);
Mailgun::send([
'from' => 'sender@example.com',
'to' => 'recipient@example.com',
'subject' => 'With Attachment',
'text' => 'Check the attachment!',
'attachment' => [
'filename' => 'file.txt',
'content' => base64_encode(file_get_contents('file.txt')),
],
]);
Dispatch a job to send emails later:
use Tolotra\Mailgun\Jobs\SendMailgunEmail;
SendMailgunEmail::dispatch([
'from' => 'sender@example.com',
'to' => 'recipient@example.com',
'subject' => 'Async Email',
'text' => 'Sent via queue!',
]);
Ensure the SendMailgunEmail job is registered in App\Console\Kernel.php:
protected $commands = [
\Tolotra\Mailgun\Jobs\SendMailgunEmail::class,
];
Use Mailgun templates (requires template ID):
Mailgun::sendTemplate('template_id', [
'from' => 'sender@example.com',
'to' => 'recipient@example.com',
'subject' => 'Template Email',
'vars' => ['name' => 'John'], // Template variables
]);
Listen for email events (e.g., Mailgun\Events\EmailSent):
use Tolotra\Mailgun\Events\EmailSent;
Event::listen(EmailSent::class, function ($event) {
Log::info('Email sent to: ' . $event->recipient);
});
Override Laravel’s default mailer in config/mail.php:
'driver' => 'mailgun',
Then use Laravel’s Mail::send() or Notification classes, which will delegate to Mailgun.
Bind a custom GuzzleHttp\Client for advanced configurations (e.g., proxies):
$client = new \GuzzleHttp\Client([
'timeout' => 30,
'proxy' => 'http://proxy.example.com',
]);
$this->app->bind(\GuzzleHttp\Client::class, function () use ($client) {
return $client;
});
Use Mailgun’s sandbox mode or mock the facade in tests:
Mailgun::shouldReceive('send')->once()->andReturn(true);
API Key Exposure:
.env or hardcode keys. Use Laravel’s .env or environment variables.sending).Rate Limits:
Mailgun\Exceptions\RateLimitExceededException gracefully:
try {
Mailgun::send([...]);
} catch (\Tolotra\Mailgun\Exceptions\RateLimitExceededException $e) {
Log::warning('Mailgun rate limit exceeded. Retrying later...');
}
Attachment Size Limits:
Async Job Failures:
php artisan queue:work) is running to process SendMailgunEmail jobs. Monitor failed jobs in the failed_jobs table.Missing Dependencies:
guzzlehttp/guzzle. If you encounter ClassNotFoundException, run:
composer require guzzlehttp/guzzle
Enable Guzzle Debugging:
Add this to config/mailgun.php to log requests:
'debug' => env('MAILGUN_DEBUG', false),
Then check Laravel logs for raw API requests/responses.
Validate API Responses: Mailgun returns HTTP status codes. Handle errors explicitly:
try {
$result = Mailgun::send([...]);
} catch (\Tolotra\Mailgun\Exceptions\MailgunException $e) {
if ($e->getCode() === 400) {
Log::error('Bad request: ' . $e->getMessage());
}
}
Check Mailgun Status: Verify your domain and API key are active in the Mailgun dashboard. Test with the Mailgun API tester.
Custom Responses:
Extend the Tolotra\Mailgun\MailgunManager class to add methods for unsupported API endpoints (e.g., lists, routes):
// app/Providers/MailgunServiceProvider.php
public function register()
{
$this->app->extend('mailgun', function ($mailgun) {
$mailgun->extend('getLists', function () {
return $this->client->get('/lists');
});
return $mailgun;
});
}
Event Customization:
Publish and modify the event class (php artisan vendor:publish --tag=mailgun-events) to add custom logic to EmailSent or EmailFailed events.
Queue Job Customization:
Override the SendMailgunEmail job to add retries or custom logic:
class CustomSendMailgunEmail extends SendMailgunEmail
{
public function retryUntil()
{
return now()->addMinutes(5); // Retry for 5 minutes
}
}
Webhook Handling: Use Mailgun’s webhooks to trigger Laravel events. Example route:
Route::post('/mailgun-webhook', function (Request $request) {
event(new \Tolotra\Mailgun\Events\WebhookReceived($request->all()));
});
How can I help you explore Laravel packages today?