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

alexbrons/swiftmailer-mailgun-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package:

    composer require cspoo/swiftmailer-mailgun-bundle php-http/guzzle5-adapter
    
  2. Register the bundle (Symfony 4+):

    // config/bundles.php
    return [
        // ...
        cspoo\Swiftmailer\MailgunBundle\cspooSwiftmailerMailgunBundle::class => ['all' => true],
    ];
    
  3. Configure Mailgun credentials (Symfony 4+):

    # config/packages/mailgun.yaml
    cspoo_swiftmailer_mailgun:
        key: '%env(MAILGUN_API_KEY)%'
        domain: '%env(MAILGUN_DOMAIN)%'
    
  4. Enable Mailgun transport in Swiftmailer:

    # config/packages/swiftmailer.yaml
    swiftmailer:
        transport: 'mailgun'
        spool: { type: 'memory' }
    
  5. Send your first email:

    use Swift_Message;
    
    $message = (new Swift_Message('Hello Email'))
        ->setFrom('noreply@example.com')
        ->setTo('recipient@example.com')
        ->setBody('Hello, this is a test email!');
    
    $this->get('mailer')->send($message);
    

First Use Case

Replace your existing mail transport with Mailgun for transactional emails (e.g., password resets, notifications). Test locally using:

bin/console swiftmailer:email:send --from=test@example.com --to=test@example.com --subject="Test" --body="Hello"

Implementation Patterns

Core Workflow

  1. Message Composition: Use Swiftmailer’s fluent API to craft emails with HTML/Plaintext bodies, attachments, and custom headers.

    $message = (new Swift_Message('Welcome'))
        ->setFrom(['noreply@domain.com' => 'Support Team'])
        ->setTo(['user@example.com' => 'User Name'])
        ->setBody($this->renderView('emails/welcome.html.twig', ['name' => 'John']))
        ->addPart($plaintextBody, 'text/plain');
    
  2. Sending Emails: Inject the mailer service (autowired in controllers) and call send():

    public function sendWelcomeEmail(User $user) {
        $message = $this->createWelcomeMessage($user);
        $this->mailer->send($message);
    }
    
  3. Batch Processing: Use Swiftmailer’s BatchSender for bulk emails (e.g., newsletters):

    $batch = new Swift_BatchSender($this->mailer, 10); // 10 emails at a time
    foreach ($users as $user) {
        $batch->send($this->createMessage($user));
    }
    

Integration Tips

  • Environment-Specific Configs: Override mailgun.yaml in config/packages/mailgun_{env}.yaml for staging/production:

    # config/packages/mailgun_prod.yaml
    cspoo_swiftmailer_mailgun:
        endpoint: 'https://api.mailgun.net'
        key: '%env(MAILGUN_PROD_KEY)%'
    
  • Event Listeners: Attach listeners to Swiftmailer events (e.g., SentEvent) for analytics or logging:

    // src/EventListener/MailgunLogger.php
    public function onSent(SentEvent $event) {
        $this->logger->info('Email sent to: ' . $event->getAddress());
    }
    
  • Testing: Use Swift_Transport_MemoryTransport in tests to avoid real API calls:

    // tests/TestCase.php
    protected function getMailer() {
        $transport = new Swift_Transport_MemoryTransport();
        return new Swift_Mailer($transport);
    }
    
  • Async Processing: Combine with Symfony Messenger for background email sending:

    // src/Message/SendEmailMessage.php
    class SendEmailMessage {
        public function __construct(private Swift_Message $message) {}
    }
    
    // src/MessageHandler/SendEmailHandler.php
    public function __invoke(SendEmailMessage $message) {
        $this->mailer->send($message->message);
    }
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never commit .env files to version control. Use env() in PHP or %env() in YAML.
    • Restrict Mailgun API key permissions to only necessary endpoints (e.g., messages.create).
  2. Spooling Quirks:

    • spool: { type: memory } sends emails only on kernel.terminate. For immediate sending, use:
      spool: null
      
    • Memory spool emails are lost on process restart (e.g., after php artisan cache:clear).
  3. HTTP Client Issues:

    • If using custom HTTP clients, ensure they support HTTPS and handle retries:
      cspoo_swiftmailer_mailgun:
          http_client: 'httplug.client' # Must be a valid service ID
      
    • Debug HTTP errors with:
      bin/console debug:config cspoo_swiftmailer_mailgun
      
  4. Rate Limiting:

    • Mailgun enforces rate limits. Monitor usage via:
      bin/console swiftmailer:spool:send --dry-run
      
  5. Domain Verification:

    • Ensure your Mailgun domain is verified to avoid emails being marked as spam.

Debugging

  • Enable Swiftmailer Debug:

    swiftmailer:
        debug: '%kernel.debug%'
    

    Logs will appear in var/log/dev.log.

  • Check Mailgun Webhooks: Configure Mailgun webhooks to debug delivery failures:

    # config/packages/mailgun.yaml
    cspoo_swiftmailer_mailgun:
        webhook_url: 'https://your-app.com/webhook/mailgun'
    
  • Validate API Responses: Use Mailgun\Mailgun::getLastResponse() to inspect raw API responses:

    $mailgun = $this->container->get('mailgun.mailgun');
    $response = $mailgun->getLastResponse();
    

Extension Points

  1. Custom Transports: Extend the bundle to support additional Mailgun features (e.g., tracking events):

    // src/Mailgun/Transport/CustomTransport.php
    class CustomTransport extends \cspoo\Swiftmailer\MailgunBundle\Transport\MailgunTransport {
        public function send(Swift_Mime_SimpleMessage $message, &$failedRecipients = null) {
            // Add custom logic (e.g., track opens)
            parent::send($message, $failedRecipients);
        }
    }
    
  2. Override Services: Replace the default Mailgun\Mailgun service in services.yaml:

    services:
        mailgun.mailgun:
            class: App\Service\CustomMailgun
            arguments:
                - '%env(MAILGUN_API_KEY)%'
                - '%env(MAILGUN_DOMAIN)%'
    
  3. Add Attachments Dynamically: Use Swiftmailer’s EmbeddedFile for inline images or Attachment for files:

    $message->embed(Swift_Image::fromPath('/path/to/image.png'));
    $message->attach(Swift_Attachment::fromPath('/path/to/file.pdf'));
    
  4. Template Inheritance: Combine with Twig to create reusable email templates:

    {# templates/emails/base.html.twig #}
    <html>
        <body>
            {{ block('content') }}
        </body>
    </html>
    
    {# templates/emails/welcome.html.twig #}
    {% extends 'emails/base.html.twig' %}
    {% block content %}
        <h1>Welcome, {{ name }}!</h1>
    {% endblock %}
    

Performance Tips

  • Batch Emails: Use Swift_BatchSender to reduce API calls:

    $batch = new Swift_BatchSender($this->mailer, 50);
    foreach ($recipients as $recipient) {
        $batch->send($this->createMessage($recipient));
    }
    
  • Async Queues: Offload email sending to a queue worker (e.g., Symfony Messenger + Redis):

    $this->messageBus->dispatch(new SendEmailMessage($message));
    
  • Caching Templates: Pre-render email templates and cache them:

    $cachedBody = $this->cache->get('email.welcome', function() use ($user) {
        return
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware