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 Mailer Laravel Package

symfony/mailgun-mailer

Symfony Mailer integration for Mailgun. Send emails via Mailgun using SMTP, HTTP, or API transports by setting MAILER_DSN with your Mailgun key, domain, and optional region. Suitable for Symfony apps needing reliable Mailgun delivery.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup for Laravel Developers

While this package is Symfony-first, Laravel developers can still leverage it in specific edge cases (e.g., legacy Symfony microservices or hybrid apps). Here’s how to integrate it minimally:

  1. Install via Composer (in a Symfony-compatible context):

    composer require symfony/mailgun-mailer
    
  2. Configure in .env (Symfony-style DSN):

    MAILER_DSN=mailgun+api://YOUR_MAILGUN_API_KEY:YOUR_DOMAIN@default?region=us
    
    • Replace YOUR_MAILGUN_API_KEY with your Mailgun API key.
    • Replace YOUR_DOMAIN with your Mailgun sending domain (e.g., example.com).
    • region is optional (defaults to us; use eu for EU region).
  3. First Use Case: Send an Email Use Symfony’s MailerInterface in a Laravel service (requires Symfony’s Mailer component):

    use Symfony\Component\Mailer\MailerInterface;
    use Symfony\Component\Mailer\Envelope;
    use Symfony\Component\Mime\Email;
    
    public function sendWelcomeEmail(MailerInterface $mailer, string $to)
    {
        $email = (new Email())
            ->from('noreply@example.com')
            ->to($to)
            ->subject('Welcome!')
            ->text('Hello!');
    
        $envelope = new Envelope(
            new Address($to),
            'noreply@example.com',
            ['X-Mailgun-Variables' => '{"user": "John"}']
        );
    
        $mailer->send($email, $envelope);
    }
    

Where to Look First

  1. DSN Configuration:

  2. Laravel-Symfony Bridge:

    • If using Laravel, explore spatie/laravel-symfony-mail to integrate Symfony’s Mailer into Laravel’s ecosystem.
    • For hybrid apps, consider a facade pattern to wrap Symfony’s MailerInterface in Laravel’s SwiftMailer abstraction.
  3. Debugging:

    • Enable Symfony’s debug mode (APP_DEBUG=true in .env) to inspect Mailgun transport logs.
    • Check Mailgun’s API Status for outages.

Implementation Patterns

Workflows for Laravel Developers

1. Hybrid Laravel-Symfony Apps

If your Laravel app interacts with a Symfony microservice (e.g., for emails), use this package in the Symfony service and expose a REST API or message queue (e.g., Laravel Horizon) for Laravel to trigger emails.

Example Workflow:

  1. Laravel dispatches a SendEmail job to a queue.
  2. Symfony microservice consumes the job and uses symfony/mailgun-mailer to send emails.
  3. Symfony returns a job-id to Laravel for tracking.

2. Laravel Service Provider Integration

To use Symfony’s MailerInterface in Laravel, register it in a service provider:

use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mailer\Transport\MailgunTransportFactory;

public function register()
{
    $this->app->singleton(MailerInterface::class, function ($app) {
        $dsn = config('mail.mailers.mailgun.dsn');
        $transport = MailgunTransportFactory::fromDsn($dsn);
        return new MailerInterface($transport);
    });
}

Config (config/mail.php):

'mailers' => [
    'mailgun' => [
        'dsn' => env('MAILER_DSN', 'mailgun+api://key:domain@default'),
    ],
],

3. Reusing Laravel’s Mail Facade with Symfony

If you must use this package in Laravel, create a custom mail facade:

use Illuminate\Support\Facades\Facade;

class SymfonyMailFacade extends Facade
{
    protected static function getFacadeAccessor()
    {
        return 'symfony.mailer';
    }
}

Register the MailerInterface as a singleton (as above) and bind it to symfony.mailer.


Integration Tips

  1. Mailgun-Specific Features:

    • Use Symfony’s Envelope to add Mailgun variables or tags:
      $envelope = new Envelope(
          new Address($to),
          'noreply@example.com',
          ['X-Mailgun-Variables' => json_encode(['user_id' => 123])]
      );
      
    • Track emails via Mailgun’s webhooks.
  2. Fallback Transports: Configure a fallback transport in Symfony’s Mailer for resilience:

    $mailer = new Mailer([
        new Transport($mailgunTransport),
        new Transport(new SmtpTransport('backup-smtp.example.com', 587)),
    ]);
    
  3. Testing:

    • Use Symfony’s TestMailer for unit tests:
      $mailer = new TestMailer();
      $mailer->send($email);
      $this->assertCount(1, $mailer->getSentEmails());
      
    • Mock the MailerInterface in Laravel’s tests:
      $this->mock(MailerInterface::class)->shouldReceive('send');
      
  4. Environment-Specific Configs: Use Laravel’s config/mail.php to switch transports dynamically:

    'mailers' => [
        'mailgun' => [
            'dsn' => env('MAILER_DSN', 'mailgun+api://key:domain@default'),
            'region' => env('MAILGUN_REGION', 'us'),
        ],
    ],
    

Gotchas and Tips

Pitfalls

  1. Dependency Conflicts:

    • Symfony mailer Version Mismatch: Laravel 10 uses symfony/mailer:^6.4, but this package requires ^7.4|^8.0. Resolving this may require:
      • Upgrading Laravel (not always feasible).
      • Using a custom Composer repository to install a compatible version.
    • Solution: Isolate the package in a Symfony microservice or use a vendor plugin to override Laravel’s symfony/mailer dependency.
  2. HTTP/1.1 Enforcement:

    • This package forces HTTP/1.1 for Mailgun API requests (fixed in v7.1.2+). If your Laravel app uses HTTP/2 (e.g., via Guzzle), this can cause:
      • Performance degradation.
      • Connection issues with Mailgun’s API.
    • Solution: Configure Symfony’s HttpClient to respect HTTP/1.1:
      $client = new HttpClient([
          'http_version' => '1.1',
      ]);
      
  3. Message Object Preservation:

    • In v8.1.0-BETA3, the package preserves the original Message object when sending. If you rely on Laravel’s SwiftMessage modifications (e.g., setBody()), ensure compatibility:
      // Laravel's SwiftMessage
      $message = (new \Swift_Message())
          ->setSubject('Test')
          ->setFrom(['from@example.com'])
          ->setTo(['to@example.com'])
          ->setBody('Hello');
      
      // Convert to Symfony's Email (if needed)
      $email = Email::fromSwiftMessage($message);
      
  4. Region-Specific Issues:

    • Mailgun’s EU region (region=eu) may have stricter IP requirements. Ensure your Laravel server’s IP is whitelisted in Mailgun’s dashboard.
    • Gotcha: The region parameter in the DSN is case-sensitive (us vs. US).
  5. Debugging Mailgun Errors:

    • Mailgun returns HTTP 400 for invalid emails. Symfony’s Mailer may not surface these errors clearly.
    • Solution: Enable Symfony’s debug mode and check the Response object:
      try {
          $mailer->send($email);
      } catch (\Symfony\Component\Mailer\Exception\TransportException $e) {
          $response = $e->getResponse();
          // Log $response->getContent() for Mailgun error details
      }
      

Debugging Tips

  1. Enable Verbose Logging: Configure Symfony’s Mailer to log transport interactions:
    $mailer = new Mailer($transport, [
        'logger' => new \Monolog\Logger('mailer
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony