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

Mailgun Laravel Package

tolotra/mailgun

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require tolotra/mailgun
    

    Publish the config file:

    php artisan vendor:publish --provider="Tolotra\Mailgun\MailgunServiceProvider"
    
  2. Configuration: Edit .env with your Mailgun API key and domain:

    MAILGUN_API_KEY=your_api_key
    MAILGUN_DOMAIN=your_domain.mailgun.org
    
  3. 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!'
    ]);
    

Where to Look First

  • Facade: Tolotra\Mailgun\Facades\Mailgun (primary entry point).
  • Config: config/mailgun.php (adjust API endpoint, timeout, etc.).
  • Documentation: Check the Mailgun HTTP API docs for unsupported features.

Implementation Patterns

Common Workflows

1. Sending Emails

  • Basic Text Email:
    Mailgun::send([
        'from'    => 'sender@example.com',
        'to'      => 'recipient@example.com',
        'subject' => 'Subject',
        'text'    => 'Plain text body',
    ]);
    
  • HTML Email:
    Mailgun::send([
        'from'    => 'sender@example.com',
        'to'      => 'recipient@example.com',
        'subject' => 'Subject',
        'html'    => '<h1>HTML Content</h1>',
    ]);
    
  • Attachments:
    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')),
        ],
    ]);
    

2. Async Sending (Queues)

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,
];

3. Templates

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
]);

4. Event Hooks

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);
});

Integration Tips

Laravel Mail Integration

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.

Customizing the Client

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;
});

Testing

Use Mailgun’s sandbox mode or mock the facade in tests:

Mailgun::shouldReceive('send')->once()->andReturn(true);

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never commit .env or hardcode keys. Use Laravel’s .env or environment variables.
    • Restrict Mailgun API key permissions to only necessary scopes (e.g., sending).
  2. Rate Limits:

    • Mailgun enforces rate limits. Handle Mailgun\Exceptions\RateLimitExceededException gracefully:
      try {
          Mailgun::send([...]);
      } catch (\Tolotra\Mailgun\Exceptions\RateLimitExceededException $e) {
          Log::warning('Mailgun rate limit exceeded. Retrying later...');
      }
      
  3. Attachment Size Limits:

  4. Async Job Failures:

    • Ensure your queue worker (php artisan queue:work) is running to process SendMailgunEmail jobs. Monitor failed jobs in the failed_jobs table.
  5. Missing Dependencies:

    • The package requires guzzlehttp/guzzle. If you encounter ClassNotFoundException, run:
      composer require guzzlehttp/guzzle
      

Debugging

  1. 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.

  2. 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());
        }
    }
    
  3. Check Mailgun Status: Verify your domain and API key are active in the Mailgun dashboard. Test with the Mailgun API tester.

Extension Points

  1. 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;
        });
    }
    
  2. Event Customization: Publish and modify the event class (php artisan vendor:publish --tag=mailgun-events) to add custom logic to EmailSent or EmailFailed events.

  3. 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
        }
    }
    
  4. 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()));
    });
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle