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

Swiftmailer Mailgun Bundle Laravel Package

dugandzic/swiftmailer-mailgun-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dugandzic/swiftmailer-mailgun-bundle
    

    (Note: The README references cspoo/swiftmailer-mailgun-bundle, but the package name in the prompt is dugandzic/swiftmailer-mailgun-bundle. Use the correct namespace in your AppKernel.php.)

  2. Register the Bundle In app/AppKernel.php:

    new \Dugandzic\Swiftmailer\MailgunBundle\DugandzicSwiftmailerMailgunBundle(),
    
  3. Configure Mailgun In config/packages/dugandzic_swiftmailer_mailgun.yaml (or config/config.yml for older Laravel):

    dugandzic_swiftmailer_mailgun:
        key: "%env(MAILGUN_API_KEY)%"  # Use .env for security
        domain: "%env(MAILGUN_DOMAIN)%"
    
  4. Update Swiftmailer Transport In the same config file:

    framework:
        mailer:
            transport: "%env(MAILER_TRANSPORT)%"  # Set to "mailgun"
    
  5. First Use Case Send a test email via Laravel’s Mail facade:

    use Illuminate\Support\Facades\Mail;
    
    Mail::raw('Test email body', function ($message) {
        $message->to('recipient@example.com')
                ->subject('Test Subject');
    });
    

Implementation Patterns

Core Workflows

  1. Mailgun-Specific Features

    • Tracking Events: Enable Mailgun’s tracking by setting:
      dugandzic_swiftmailer_mailgun:
          track_opens: true
          track_clicks: true
      
    • Attachments: Use Swiftmailer’s native attachment methods (e.g., $message->attach()). Mailgun handles file uploads automatically.
  2. Environment-Based Configuration Use .env for dynamic keys/domains:

    MAILGUN_API_KEY=key-xxxxxxxxxx
    MAILGUN_DOMAIN=mydomain.com
    MAILER_TRANSPORT=mailgun
    
  3. Queueing Emails Pair with Laravel’s queue system for async sending:

    Mail::to('user@example.com')->queue(new OrderShipped($order));
    
  4. Custom Headers Inject Mailgun-specific headers (e.g., X-Mailgun-Variables):

    $message->getHeaders()->addTextHeader('X-Mailgun-Variables', '{"user_id": 123}');
    

Integration Tips

  • Laravel Notifications: Extend Mailable to use Mailgun’s features:
    public function build()
    {
        return $this->markdown('emails.order')
                    ->with(['tracking' => true]);
    }
    
  • Webhook Handling: Use Mailgun’s webhooks (configured in Mailgun dashboard) to trigger Laravel events. Example listener:
    public function handle(IncomingMailgunWebhook $event)
    {
        // Process event (e.g., "clicked", "delivered")
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Security

    • Never hardcode keys in config.yml. Always use .env or Laravel’s env() helper.
    • Restrict Mailgun API key permissions to only what’s needed (e.g., sending scope).
  2. Domain Mismatch

    • Ensure the domain in config matches the Mailgun domain you’re using. Errors like Invalid domain often stem from this.
  3. Rate Limits

    • Mailgun enforces rate limits. Monitor usage via Mailgun dashboard or logs.
  4. Spoofing Protection

    • Mailgun requires SPF/DKIM/DMARC records. Configure these in your DNS to avoid deliverability issues.

Debugging

  • Enable Logging Add to config/logging.php:

    'channels' => [
        'mailgun' => [
            'driver' => 'single',
            'path' => storage_path('logs/mailgun.log'),
            'level' => 'debug',
        ],
    ],
    

    Then log Mailgun responses:

    \Log::channel('mailgun')->debug('Mailgun response:', $response);
    
  • Test Mode Use Mailgun’s sandbox domain (*.mailgun.org) for testing to avoid real sends.

Extension Points

  1. Custom Transports Extend the bundle’s MailgunTransport to add features:

    class CustomMailgunTransport extends \Dugandzic\Swiftmailer\MailgunBundle\MailgunTransport
    {
        public function __construct($apiKey, $domain, $customOption)
        {
            parent::__construct($apiKey, $domain);
            $this->customOption = $customOption;
        }
    }
    
  2. Event Listeners Subscribe to Swiftmailer events (e.g., SentEvent) to log or modify emails:

    $mailer->getTransport()->getEventDispatcher()->addListener(
        'sent',
        function ($event) {
            // Custom logic (e.g., analytics)
        }
    );
    
  3. Override Templates Use Mailgun’s template variables in Laravel:

    $message->setFrom('noreply@mydomain.com')
            ->setTemplateId('welcome_template');
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope