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

Laravel dev tool to preview and inspect Mailables and Notifications without triggering them in your app. Register emails in a generated routes/mailbook.php file (with DI or closures) and browse previews at /mailbook.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package in your Laravel project:

    composer require --dev xammie/mailbook
    
  2. Run the installer to generate the route file:

    php artisan mailbook:install
    

    This creates routes/mailbook.php where you register mailables.

  3. Register a mailer in routes/mailbook.php:

    use App\Mail\VerificationMail;
    use Xammie\Mailbook\Facades\Mailbook;
    
    Mailbook::add(VerificationMail::class);
    
  4. Access the UI at /mailbook to preview your emails.

First Use Case: Previewing a Mailable

  • Register a Mailable or Notification class.
  • Visit /mailbook to see a categorized list of all registered emails.
  • Click on an email to preview its rendered HTML in an iframe.

Implementation Patterns

Core Workflows

1. Registering Mailables

  • Basic Registration:
    Mailbook::add(App\Mail\WelcomeMail::class);
    
  • With Custom Parameters:
    Mailbook::add(function () {
        $user = User::factory()->create();
        return new App\Mail\WelcomeMail($user);
    });
    
  • For Notifications:
    Mailbook::add(App\Notifications\InvoicePaidNotification::class);
    

2. Grouping and Categorizing

  • Group by Category:
    Mailbook::category('User Notifications')
        ->group(function () {
            Mailbook::add(App\Mail\WelcomeMail::class);
            Mailbook::add(App\Mail\PasswordResetMail::class);
        });
    
  • Group with Shared Recipient:
    Mailbook::to('test@example.com')
        ->group(function () {
            Mailbook::add(App\Mail\WelcomeMail::class);
            Mailbook::add(App\Mail\NewsletterMail::class);
        });
    

3. Variants for Testing Scenarios

  • Define Variants:
    Mailbook::add(App\Mail\OrderConfirmationMail::class)
        ->variant('Single Item', fn () => new App\Mail\OrderConfirmationMail(Order::factory()->withOneItem()->create()))
        ->variant('Multiple Items', fn () => new App\Mail\OrderConfirmationMail(Order::factory()->withMultipleItems()->create()));
    

4. Localization Support

  • Configure supported locales in config/mailbook.php:
    'locales' => [
        'en' => 'English',
        'nl' => 'Dutch',
    ],
    
  • Switch locales via the dropdown in the Mailbook UI.

5. Database Rollback

  • Enable in config/mailbook.php:
    'database_rollback' => true,
    
  • Safely use factories/models without persisting changes:
    Mailbook::add(function () {
        $order = Order::factory()->create(); // Changes rolled back after preview
        return new App\Mail\OrderShippedMail($order);
    });
    

6. Sending Emails

  • Enable sending in config/mailbook.php:
    'send' => true,
    'send_to' => 'test@example.com',
    
  • Click the "Send" button in the UI to dispatch the email via Laravel’s mail driver.

Integration Tips

  • Testing: Use Mailbook in your phpunit.xml to preview emails during tests:
    <env name="MAILBOOK_ENABLED" value="true"/>
    
  • CI/CD: Exclude Mailbook from production builds (it’s a dev dependency).
  • Custom Views: Publish and override Mailbook’s Blade views:
    php artisan vendor:publish --tag="mailbook-views"
    
  • Authentication: Protect /mailbook with middleware (e.g., auth) by modifying the route in routes/mailbook.php.

Gotchas and Tips

Pitfalls

  1. Database Rollback Scope:

    • Only rolls back changes made inside the closure passed to Mailbook::add().
    • Avoid mixing rollback-enabled and non-rollback code in the same closure.
  2. Queueable Mailables:

    • Mailables implementing ShouldQueue may not render correctly if the queue driver isn’t properly mocked.
    • Ensure your test environment’s queue driver is configured (e.g., sync for testing).
  3. Localization Quirks:

    • The locale dropdown only appears if locales is configured in mailbook.php.
    • Ensure your app’s locale is set correctly in AppServiceProvider for consistent previews.
  4. Attachment Handling:

    • Embedded attachments (e.g., images) may not display if the public_path() or storage_path() isn’t accessible.
    • Use absolute paths for attachments in development:
      $mail->embed(file_get_contents(public_path('images/logo.png')), 'logo');
      
  5. Route Conflicts:

    • The /mailbook route is registered automatically. Avoid naming other routes /mailbook to prevent conflicts.

Debugging Tips

  • Blank Preview?:

    • Check if the mailer class exists and is autoloaded.
    • Verify the closure returns a valid Mailable or Notification instance.
    • Look for PHP errors in Laravel’s log (storage/logs/laravel.log).
  • Database Rollback Issues:

    • Ensure database_rollback is true in mailbook.php.
    • Avoid transactions or manual commits outside the closure.
  • Send Button Missing:

    • Confirm 'send' => true and 'send_to' are set in mailbook.php.
    • Verify your mail driver (e.g., log, mailgun) is configured in .env.

Extension Points

  1. Customize the UI:

    • Override views in resources/views/vendor/mailbook/:
      php artisan vendor:publish --tag="mailbook-views"
      
    • Modify the iframe’s styling or add custom JavaScript.
  2. Add Metadata:

    • Extend the Mailbook facade to include custom metadata (e.g., tags, descriptions) for each mailer:
      Mailbook::add(WelcomeMail::class)
          ->meta(['priority' => 'high', 'template' => 'welcome_v2']);
      
  3. Hook into Mailbook Events:

    • Listen for mailbook.mail.preview or mailbook.mail.sent events to log or modify behavior:
      Mailbook::add(WelcomeMail::class)
          ->listener(function ($mail) {
              // Log or modify $mail before rendering
          });
      
  4. Dynamic Registration:

    • Register mailables dynamically based on conditions (e.g., feature flags):
      if (config('features.newsletter')) {
          Mailbook::add(App\Mail\NewsletterMail::class);
      }
      
  5. Testing Utilities:

    • Create a helper trait for tests:
      trait MailbookTestHelper {
          public function registerMailForTest($mailable, $user = null) {
              if ($user) Mailbook::to($user);
              Mailbook::add($mailable);
          }
      }
      
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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