Weave 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

Mail Bundle Laravel Package

braune-digital/mail-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install Dependencies Run composer require braune-digital/mail-bundle and ensure doctrine/orm, sonata-project/easy-extends, and braune-digital/translation-base-bundle are installed. Verify SonataAdmin is installed if backend management is needed.

  2. Enable Bundles Add to config/bundles.php (or AppKernel.php for Symfony <5.0):

    BrauneDigital\TranslationBaseBundle\BrauneDigitalTranslationBaseBundle::class,
    BrauneDigital\MailBundle\BrauneDigitalMailBundle::class,
    
  3. Generate Extensions Run:

    php bin/console sonata:easy-extends:generate --dest=src BrauneDigitalMailBundle
    

    Enable the extended bundle in config/bundles.php:

    Application\BrauneDigital\MailBundle\BrauneDigitalMailBundle::class,
    
  4. Configure Add to config/packages/braune_digital_mail.yaml:

    braune_digital_mail:
        user_class: App\Entity\User
        base_template_path: "%kernel.project_dir%/templates/emails"
    
  5. First Use Case Create a template file (e.g., welcome.txt.twig) in templates/emails/ and reference it in a controller:

    use BrauneDigital\MailBundle\Mailer\MailerService;
    
    class MailController extends AbstractController {
        public function sendWelcome(MailerService $mailer) {
            $mailer->send('welcome', '[email protected]', ['name' => 'John']);
        }
    }
    

Implementation Patterns

Core Workflows

  1. Template Management

    • Store templates in templates/emails/ (e.g., welcome.html.twig, welcome.txt.twig).
    • Use Twig syntax for dynamic content:
      {# templates/emails/welcome.html.twig #}
      <h1>Hello, {{ name }}!</h1>
      
  2. Sending Emails

    • Inject MailerService into controllers/services:
      $mailer->send(
          'welcome',          // Template name (without extension)
          '[email protected]',
          ['name' => 'Alice'], // Variables
          ['subject' => 'Welcome!'] // Optional overrides
      );
      
    • Supports attachments:
      $mailer->sendWithAttachment('invoice', '[email protected]', [], [
          'attachments' => ['/path/to/file.pdf' => 'invoice.pdf']
      ]);
      
  3. Translations

    • Leverage BrauneDigitalTranslationBaseBundle for multi-language templates.
    • Place translation files in translations/emails/ (e.g., welcome.en.yml):
      welcome:
          subject: "Welcome, {{ name }}!"
      
  4. SonataAdmin Integration

    • Templates are listed in the admin panel under Mail > Templates.
    • Preview templates directly in the backend.
  5. Dynamic Recipients

    • Fetch recipients from Doctrine entities:
      $users = $entityManager->getRepository(User::class)->findAll();
      foreach ($users as $user) {
          $mailer->send('newsletter', $user->getEmail(), ['user' => $user]);
      }
      

Integration Tips

  • Event Listeners Trigger emails on entity events (e.g., user registration):

    // src/EventListener/RegistrationListener.php
    public function onRegistration(RegistrationEvent $event) {
        $mailer->send('welcome', $event->getUser()->getEmail(), ['name' => $event->getUser()->getName()]);
    }
    
  • Queueing Emails Use Symfony Messenger to defer email sending:

    $message = new SendMailMessage('welcome', '[email protected]', ['name' => 'Bob']);
    $bus->dispatch($message);
    
  • Testing Mock MailerService in tests:

    $mailer = $this->createMock(MailerService::class);
    $mailer->expects($this->once())
           ->method('send')
           ->with('welcome', '[email protected]', ['name' => 'Test']);
    

Gotchas and Tips

Pitfalls

  1. Template Path Configuration

    • Forgetting to set base_template_path in config will cause Twig\Error\LoaderError.
    • Fix: Ensure the path is absolute (e.g., %kernel.project_dir%/templates/emails).
  2. Caching Issues

    • Twig templates may not update immediately due to caching.
    • Fix: Clear cache after adding new templates:
      php bin/console cache:clear
      
  3. SonataAdmin Dependencies

    • The bundle requires SonataEasyExtends and SonataAdmin for backend features.
    • Fix: Install missing bundles if the admin panel doesn’t appear.
  4. Translation Overrides

    • Template variables (e.g., {{ name }}) in translations may not render if the variable isn’t passed.
    • Fix: Ensure all required variables are included in the send() call.
  5. User Class Mismatch

    • If user_class in config doesn’t match your actual user entity, the admin panel may fail.
    • Fix: Verify the FQCN (e.g., App\Entity\User).

Debugging

  • Check Logs Enable debug mode (APP_DEBUG=true) to log template loading errors:

    php bin/console debug:config braune_digital_mail
    
  • Template Not Found If a template isn’t found, check:

    • The filename matches exactly (e.g., welcome.html.twig, not welcome.twig).
    • The base_template_path is correct.
  • SonataAdmin Permissions Ensure the user has access to the Mail admin section in Sonata.

Extension Points

  1. Custom Mailer Extend MailerService to add logic (e.g., logging, analytics):

    class CustomMailerService extends MailerService {
        public function send(string $template, string $to, array $vars = [], array $options = []) {
            // Add custom logic (e.g., track sends)
            parent::send($template, $to, $vars, $options);
        }
    }
    
  2. Dynamic Template Selection Override template selection logic in a custom service:

    $mailer->setTemplateResolver(new CustomTemplateResolver());
    
  3. Add Fields to Admin Extend the Sonata admin class to add custom fields:

    // src/Admin/MailTemplateAdmin.php
    protected function configureFormFields(FormMapper $formMapper) {
        $formMapper->add('custom_field', 'text');
    }
    
  4. Hook into Email Events Dispatch events before/after sending:

    $mailer->onSend(function (SendMailEvent $event) {
        // Log or modify the email
    });
    

Performance Tips

  • Precompile Templates Use twig:compile to precompile templates for faster rendering:

    php bin/console twig:compile
    
  • Batch Processing For bulk emails, use chunking to avoid memory issues:

    $users = $entityManager->getRepository(User::class)->findAll();
    array_chunk($users, 100, function ($chunk) use ($mailer) {
        foreach ($chunk as $user) {
            $mailer->send('newsletter', $user->getEmail(), ['user' => $user]);
        }
    });
    
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.
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
adachsoft/php-code-style