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

Mailbook Laravel Package

xammie/mailbook

Mailbook is a Laravel dev package for previewing and inspecting mailables and email notifications without triggering them in your app. Register mails via a routes file (with DI or closures) and view them at /mailbook.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev xammie/mailbook
    php artisan mailbook:install
    

    This creates routes/mailbook.php and publishes the default configuration.

  2. First Use Case: Register a mailable in routes/mailbook.php:

    use App\Mails\WelcomeMail;
    use Xammie\Mailbook\Facades\Mailbook;
    
    Mailbook::add(WelcomeMail::class);
    

    Visit /mailbook to preview the mail.


Key First Steps

  • Register Mailable/Notification:
    Mailbook::add(App\Notifications\InvoicePaidNotification::class);
    
  • Set Recipient (for notifications):
    Mailbook::to('user@example.com')->add(WelcomeNotification::class);
    
  • Access UI: Navigate to /mailbook to view and test emails.

Implementation Patterns

Core Workflows

  1. Registering Mails:

    • Direct Class Registration:
      Mailbook::add(VerificationMail::class); // Auto-injects dependencies
      
    • Closure-Based Registration (for dynamic data):
      Mailbook::add(function () {
          $user = User::factory()->make();
          return new WelcomeMail($user);
      });
      
  2. Grouping and Categorization:

    Mailbook::category('Onboarding')
        ->group(function () {
            Mailbook::add(WelcomeMail::class);
            Mailbook::add(VerificationMail::class);
        });
    
  3. Variants for Testing Scenarios:

    Mailbook::add(OrderMail::class)
        ->variant('Single Item', fn () => new OrderMail(Order::factory()->withOneItem()->create()))
        ->variant('Multiple Items', fn () => new OrderMail(Order::factory()->withMultipleItems()->create()));
    
  4. Database Rollback (for safe testing):

    // In config/mailbook.php
    'database_rollback' => true,
    

    Use factories freely in closures—changes auto-rollback after rendering.


Integration Tips

  • Localization Support: Configure supported locales in config/mailbook.php:

    'locales' => [
        'en' => 'English',
        'nl' => 'Dutch',
    ],
    

    Users can switch languages via the UI dropdown.

  • Sending Real Emails (for testing): Enable in config/mailbook.php:

    'send' => true,
    'send_to' => 'test@example.com',
    

    Adds a "Send" button to dispatch emails via your default mail driver.

  • Testing Queued Mails: Ensure ShouldQueue mailables work by mocking the queue in tests:

    Mailbook::add(QueuedMail::class);
    // Queue is automatically handled during preview.
    
  • Embedded Attachments: Mailbook now correctly handles embedded attachments (fixed in v1.11.1). Ensure your mailables use the embed() method properly:

    $mail->embed(public_path('images/logo.png'), 'logo');
    

Gotchas and Tips

Common Pitfalls

  1. Database Rollback Issues:

    • Problem: Rollback fails if exceptions occur in closures.
    • Fix: Wrap logic in try-catch or ensure no unhandled exceptions:
      Mailbook::add(function () {
          try {
              $order = Order::factory()->create();
              return new OrderMail($order);
          } catch (\Exception $e) {
              Log::error($e);
              throw $e; // Re-throw to prevent silent failures
          }
      });
      
  2. Missing Dependencies:

    • Problem: Closures without proper dependency injection may fail.
    • Fix: Use app() or pass dependencies explicitly:
      Mailbook::add(function () {
          $service = app(VerificationService::class);
          return new VerificationMail($service);
      });
      
  3. Localization Not Showing:

    • Problem: Locales dropdown missing.
    • Fix: Publish and configure config/mailbook.php:
      php artisan vendor:publish --tag="mailbook-config"
      
  4. Queued Mails Not Rendering:

    • Problem: ShouldQueue mailables appear blank.
    • Fix: Ensure the queue driver is configured and the mailable’s handle() method is callable:
      // In tests, mock the queue if needed:
      Queue::fake();
      
  5. Embedded Attachments Not Displaying:

    • Problem: Embedded attachments (e.g., images) not showing in previews.
    • Fix: Verify the embed() method is called before send() or to() in your mailable. The fix in v1.11.1 ensures proper replacement of embedded content.

Debugging Tips

  • Inspect Mailbook Routes: Run php artisan route:list | grep mailbook to verify the /mailbook route is registered.

  • Check Published Config: After publishing, verify config/mailbook.php for customizations:

    php artisan vendor:publish --tag="mailbook-config"
    
  • Clear Cache: If changes aren’t reflected, clear Laravel’s cache:

    php artisan cache:clear
    php artisan view:clear
    
  • Test Embedded Content: Ensure your mailables use the embed() method correctly. Example:

    public function build()
    {
        return $this->subject('Test Email')
                    ->embed(public_path('images/logo.png'), 'logo')
                    ->view('emails.test');
    }
    

Extension Points

  1. Custom Views: Publish and override views:

    php artisan vendor:publish --tag="mailbook-views"
    

    Modify resources/views/vendor/mailbook/ to change UI elements.

  2. Domain Configuration: Set a custom domain for mail previews (e.g., for URL testing):

    // config/mailbook.php
    'domain' => 'mailbook.test',
    
  3. Event Listeners: Extend Mailbook’s behavior by listening to its events (e.g., MailbookRendering):

    use Xammie\Mailbook\Events\MailbookRendering;
    
    event(new MailbookRendering($mailable));
    

Pro Tips

  • Test Edge Cases: Use variants to simulate different states (e.g., empty cart, failed payment):

    Mailbook::add(CartMail::class)
        ->variant('Empty Cart', fn () => new CartMail([]))
        ->variant('Items in Cart', fn () => new CartMail([Item::factory()->make()]));
    
  • Combine with Laravel Forge/Portainer: Deploy Mailbook in staging environments for team-wide email testing.

  • CI/CD Integration: Add Mailbook to your test suite to catch email regressions:

    // In tests/Feature/MailbookTest.php
    public function test_all_mailables_render()
    {
        $response = $this->get('/mailbook');
        $response->assertStatus(200);
    }
    
  • Leverage Tailwind Updates: The latest Tailwind upgrade (v1.11.1) may introduce UI improvements. Customize the published views to align with your project’s design system.

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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4