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

Swift Reader Bundle Laravel Package

cocorico/swift-reader-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Run in your Laravel project (adapted for Laravel's Composer usage):

    composer require --dev cocorico/swift-reader-bundle
    

    (Note: Laravel uses composer require instead of Symfony's php composer.phar require.)

  2. Enable the Bundle Add to config/app.php under extra.bundles (Laravel 5.x) or use a service provider in config/app.php:

    'providers' => [
        // ...
        Cocorico\SwiftReaderBundle\CocoricoSwiftReaderBundle::class,
    ],
    

    (Laravel does not use AppKernel.php; bundles are registered via service providers.)

  3. Configure Routing Add the route to routes/web.php (Laravel 5.5+):

    Route::group([
        'prefix' => '_cocorico_swift_reader',
        'middleware' => ['web', 'dev'], // Only in dev/test
    ], function () {
        $router->mount(Cocorico\SwiftReaderBundle\CocoricoSwiftReaderBundle::class, '/_cocorico_swift_reader');
    });
    

    (Laravel's routing is more flexible; adjust middleware as needed.)

  4. Configure Storage Path Add to config/services.php or a custom config file:

    'cocorico_swift_reader' => [
        'path' => storage_path('app/swift_emails'),
    ],
    

    (Laravel uses storage_path() for consistency with its filesystem.)

  5. Trigger Emails Send a test email via Swift Mailer (e.g., Mail::to('user@example.com')->send(new TestEmail())).

  6. Access the Toolbar Visit /_cocorico_swift_reader in your browser (only in dev or test environments).


First Use Case

Debugging Email Content

  • Send a test email (e.g., a password reset or welcome email).
  • Open the Swift Reader tab in the Laravel Debugbar (or standalone toolbar if configured).
  • Inspect the raw email structure, headers, and body to verify content, attachments, or formatting.

Implementation Patterns

Workflows

  1. Development Workflow

    • Send & Debug: Use the toolbar to inspect emails during feature development (e.g., newsletter templates, transactional emails).
    • Template Testing: Validate HTML/CSS rendering by comparing the rendered email with the Swift Reader output.
    • Attachment Verification: Check if attachments are correctly embedded or linked.
  2. Testing Workflow

    • Unit/Feature Tests: Mock Swift Mailer and assert email content using the bundle’s storage path:
      $emailPath = storage_path('app/swift_emails/latest.eml');
      $this->assertFileExists($emailPath);
      $this->assertStringContainsString('Expected Content', file_get_contents($emailPath));
      
    • CI/CD Integration: Disable the bundle in production by removing it from config/app.php and adding it conditionally:
      if (app()->environment(['local', 'testing'])) {
          $bundles[] = Cocorico\SwiftReaderBundle\CocoricoSwiftReaderBundle::class;
      }
      
  3. Integration with Laravel Mail

    • Custom Mailables: Extend Laravel’s Mailable class and use Swift Reader to debug:
      Mail::to('user@example.com')->send(new OrderConfirmation($order));
      
    • Queue Delayed Emails: Verify queued emails by processing them manually:
      php artisan queue:work --once
      

Integration Tips

  • Debugbar Compatibility If using barryvdh/laravel-debugbar, ensure the bundle’s toolbar integrates by checking for conflicts in resources/js/app.js or app/Providers/AppServiceProvider.php:

    Debugbar::disable(); // Temporarily disable if conflicts arise
    
  • Storage Permissions Ensure the configured storage path is writable:

    mkdir -p storage/app/swift_emails
    chmod -R 775 storage/app/swift_emails
    
  • Environment-Specific Config Use Laravel’s environment configs (config/swift_reader.php) to toggle the bundle:

    'enabled' => env('SWIFT_READER_ENABLED', false),
    
  • Customizing Email Storage Override the default storage logic by binding a custom Swift_Transport in AppServiceProvider:

    $this->app->bind('swift.transport', function () {
        $transport = new Swift_SmtpTransport('smtp.example.com', 587);
        // Custom logic to log emails
        return $transport;
    });
    

Gotchas and Tips

Pitfalls

  1. Environment Mismatch

    • Issue: The toolbar may not appear in local or testing environments if not explicitly enabled.
    • Fix: Add 'dev' to the middleware in routes/web.php:
      'middleware' => ['web', 'dev'],
      
  2. Swift Mailer Not Configured

    • Issue: Emails won’t appear in the toolbar if Swift Mailer isn’t properly set up.
    • Fix: Ensure config/mail.php has valid transport settings (e.g., SMTP or Mailgun).
  3. Storage Path Overrides

    • Issue: Emails may not save if the path is misconfigured or inaccessible.
    • Fix: Use Laravel’s storage_path() helper and verify permissions:
      'path' => storage_path('app/swift_emails'),
      
  4. Debugbar Conflicts

    • Issue: The toolbar may not render if another package (e.g., laravel-debugbar) overrides the profiler.
    • Fix: Check for duplicate toolbar registrations in AppServiceProvider:
      if (!class_exists('Cocorico\SwiftReaderBundle\CocoricoSwiftReaderBundle')) {
          // Fallback logic
      }
      
  5. Email Not Captured

    • Issue: Emails sent via Mail::raw() or Mail::send() may not appear.
    • Fix: Ensure the bundle’s event listener is subscribed to Swift Mailer’s events. Override the transport:
      $this->app->bind('swift.mailer', function () {
          $mailer = new Swift_Mailer($this->app->make('swift.transport'));
          // Add event listeners if needed
          return $mailer;
      });
      

Debugging Tips

  • Log Email Events Add a listener to log emails sent via Swift Mailer:

    Swift_Events_EventListener::register(Swift_Events_EventListener::EVENT_AFTER_SENDING, function ($event) {
        \Log::debug('Email sent to: ' . $event->getMessage()->getTo());
    });
    
  • Inspect Raw Emails Use the CLI to read stored emails:

    cat storage/app/swift_emails/latest.eml
    
  • Clear Old Emails Manually clear the storage directory or add a command:

    Artisan::command('swift:clear', function () {
        File::cleanDirectory(storage_path('app/swift_emails'));
    });
    

Extension Points

  1. Custom Email Processor Extend the bundle’s storage logic by overriding the Cocorico\SwiftReaderBundle\Storage\EmailStorage service:

    $this->app->bind('cocorico_swift_reader.storage', function () {
        return new CustomEmailStorage(storage_path('app/swift_emails'));
    });
    
  2. Add Metadata to Emails Annotate emails with custom data (e.g., user ID, order ID) by extending the Email model:

    class CustomEmail extends Cocorico\SwiftReaderBundle\Model\Email
    {
        public function setMetadata(array $metadata) {
            $this->metadata = $metadata;
        }
    }
    
  3. API Endpoint for Emails Create a Laravel API route to fetch emails programmatically:

    Route::get('/api/emails', function () {
        $storage = $this->app->make('cocorico_swift_reader.storage');
        return response()->json($storage->getEmails());
    });
    
  4. Filter Emails by Criteria Add a repository layer to query emails by subject, recipient, or date:

    class EmailRepository {
        public function findByRecipient($email) {
            $storage = $this->app->make('cocorico_swift_reader.storage');
            return $storage->getEmails()->filter(function ($emailObj) use ($email) {
                return in_array($email, $emailObj->getTo());
            });
        }
    }
    
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.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky