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

Twig Mailer Bundle Laravel Package

cooperspeele/twig-mailer-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cooperspeele/twig-mailer-bundle
    

    Add to config/bundles.php (Symfony):

    Cooperspeele\TwigMailerBundle\TwigMailerBundle::class => ['all' => true],
    
  2. Configure Twig Mailer Update config/packages/twig_mailer.yaml (Symfony) or manually configure in Laravel via config/twig_mailer.php:

    twig_mailer:
        mailer: 'mailer' // Laravel's default mailer
        from_address: 'noreply@example.com'
        from_name: 'Your App'
    
  3. First Use Case Create a Twig template (resources/views/emails/welcome.twig):

    <html>
        <body>
            <h1>Welcome, {{ name }}!</h1>
        </body>
    </html>
    

    Send an email in Laravel:

    use Cooperspeele\TwigMailerBundle\Mailer\TwigMailer;
    
    $mailer = app(TwigMailer::class);
    $mailer->send('emails.welcome', ['name' => 'John'], 'Welcome Email', [
        'to' => 'user@example.com'
    ]);
    

Implementation Patterns

Workflows

  1. Template-Based Emails

    • Store all email templates in resources/views/emails/ with .twig extension.
    • Use Twig syntax for dynamic content (e.g., {{ user.name }}).
  2. Reusable Components

    • Create partials (e.g., header.twig, footer.twig) in resources/views/emails/_partials/.
    • Include them in templates:
      {% include '_partials/header.twig' %}
      
  3. Dynamic Recipients

    • Loop through users in Twig:
      {% for user in users %}
          <p>{{ user.email }}: {{ user.message }}</p>
      {% endfor %}
      
    • Pass an array of recipients in Laravel:
      $mailer->send('emails/newsletter', ['users' => $users], 'Newsletter', [
          'to' => ['user1@example.com', 'user2@example.com']
      ]);
      
  4. Attachments

    • Attach files via Laravel’s Mailable or directly:
      $mailer->send('emails/invoice', ['invoice' => $invoice], 'Invoice', [
          'to' => 'client@example.com',
          'attachments' => ['/path/to/invoice.pdf' => 'invoice.pdf']
      ]);
      
  5. Queueing Emails

    • Use Laravel’s queue system with the Twig mailer:
      $mailer->queue('emails/welcome', ['name' => 'John'], 'Welcome Email', [
          'to' => 'user@example.com'
      ]);
      

Integration Tips

  • Laravel Notifications: Extend Mailable to use TwigMailer:

    public function build()
    {
        return $this->markdown('emails.welcome')
                    ->with(['name' => $this->user->name]);
    }
    

    (Note: Requires minor adjustments to use Twig instead of Blade.)

  • Testing: Use Laravel’s MailFake or mock TwigMailer in tests:

    $mailer = Mockery::mock(TwigMailer::class);
    $mailer->shouldReceive('send')->once();
    

Gotchas and Tips

Pitfalls

  1. Twig vs. Blade Confusion

    • The bundle uses Twig, not Blade. Avoid mixing syntax (e.g., @foreach won’t work).
    • Fix: Stick to Twig tags ({% %}) and functions ({{ }}).
  2. Mailer Configuration Overrides

    • If mailer key in twig_mailer.yaml is misconfigured, emails may fail silently.
    • Debug: Check Laravel’s config/mail.php for valid transport settings (e.g., mailgun, ses).
  3. Template Paths

    • Twig templates must be in resources/views/emails/ or a custom path configured in the bundle.
    • Fix: Set twig_mailer.template_path in config if using a non-standard path.
  4. Caching Issues

    • Twig templates aren’t auto-reloaded in development. Clear cache after changes:
      php artisan view:clear
      
  5. Recipient Format

    • The to parameter expects an array or string (e.g., ['user@example.com'] or 'user@example.com').
    • Gotcha: Passing a raw string without brackets may cause errors.

Debugging

  • Enable Twig Debugging: Add to config/twig_mailer.php:

    twig_mailer:
        debug: true
    

    Errors will show detailed Twig stack traces.

  • Log Sent Emails: Use Laravel’s mail log:

    Mail::pretend(true); // Log emails instead of sending
    

Extension Points

  1. Custom Twig Extensions Add extensions in config/twig_mailer.php:

    twig_mailer:
        twig:
            extensions:
                - App\Twig\CustomExtension
    
  2. Override Mailer Class Bind a custom mailer in AppServiceProvider:

    $this->app->bind(TwigMailer::class, function ($app) {
        return new CustomTwigMailer($app['mailer'], $app['twig']);
    });
    
  3. Event Listeners Listen for TwigMailerEvents (if the bundle emits them) or wrap the mailer in a decorator for pre/post-send logic.

Performance Tips

  • Precompile Twig Templates: Run php artisan twig:compile to cache templates (useful for production).
  • Batch Emails: For bulk sends, queue emails with delays to avoid rate limits:
    $mailer->later(now()->addMinutes(5), 'emails/newsletter', [...], 'Newsletter', ['to' => $recipients]);
    
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime