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

Mail Bundle Laravel Package

donkeycode/mail-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require donkeycode/mail-bundle

Register the bundle in config/bundles.php (Symfony 4+):

DonkeyCode\MailBundle\DonkeyCodeMailBundle::class => ['all' => true],
  1. Configuration: Add to config/packages/donkey_code_mail.yaml (Symfony 4+):

    donkey_code_mail:
        mail_from: 'noreply@example.com'
        reply_to: 'contact@example.com'
        options:
            header_bg: '#2d7cff'
            header_txt_color: '#ffffff'
    
  2. First Use Case: Create a Twig template at templates/Mails/invoice.html.twig:

    {% block subject %}Invoice #{{ invoiceId }}{% endblock %}
    {% block body %}
        {% embed "@DonkeyCodeMail/Mails/layout.html.twig" %}
            {% block title %}Your Invoice{% endblock %}
            {% block content %}
                <p>Invoice details...</p>
            {% endblock %}
        {% endembed %}
    {% endblock %}
    

    Send the email in a controller:

    use DonkeyCode\MailBundle\Mailer;
    
    public function sendInvoice(Mailer $mailer, int $invoiceId)
    {
        $mailer->createMessage()
            ->setTemplate('Mails/invoice.html.twig', ['invoiceId' => $invoiceId])
            ->setTo('customer@example.com')
            ->send();
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Templates: Use Twig variables to customize emails dynamically:

    {% block subject %}Welcome, {{ user.name }}{% endblock %}
    {% block body %}
        {% embed "@DonkeyCodeMail/Mails/layout.html.twig" %}
            {% block content %}
                <h1>Hello {{ user.name }}!</h1>
                <p>Your account: {{ user.email }}</p>
            {% endblock %}
        {% endembed %}
    {% endblock %}
    

    Pass data via setTemplate():

    ->setTemplate('Mails/welcome.html.twig', ['user' => $user])
    
  2. Reusable Layouts: Extend the default layout (@DonkeyCodeMail/Mails/layout.html.twig) by overriding blocks:

    {% extends "@DonkeyCodeMail/Mails/layout.html.twig" %}
    {% block footer %}
        <p>© {{ year }} Your Company</p>
    {% endblock %}
    
  3. Attachments: Attach files to emails (if supported by SwiftMailer):

    ->addAttachment('/path/to/file.pdf', 'invoice.pdf')
    
  4. CC/BCC:

    ->setCc(['cc@example.com'])
    ->setBcc(['bcc@example.com'])
    
  5. Async Sending: Use Symfony’s Messenger component to queue emails for background processing:

    $message = $mailer->createMessage()
        ->setTemplate('Mails/newsletter.html.twig', [])
        ->setTo($recipient);
    $this->messageBus->dispatch($message);
    

Integration Tips

  • Symfony Forms: Validate email inputs and pass them directly to setTo():

    $form = $this->createForm(ContactType::class);
    if ($form->isSubmitted() && $form->isValid()) {
        $mailer->createMessage()
            ->setTemplate('Mails/contact.html.twig', ['contact' => $form->getData()])
            ->setTo($this->getParameter('contact_email'))
            ->send();
    }
    
  • Event Listeners: Trigger emails on entity events (e.g., postPersist):

    // src/EventListener/UserListener.php
    public function onUserCreated(UserCreatedEvent $event)
    {
        $mailer->createMessage()
            ->setTemplate('Mails/registration.html.twig', ['user' => $event->getUser()])
            ->setTo($event->getUser()->getEmail())
            ->send();
    }
    
  • Testing: Mock the mailer service in PHPUnit:

    $mailer = $this->createMock(Mailer::class);
    $mailer->expects($this->once())
        ->method('send')
        ->willReturn(true);
    $this->container->set('donkeycode.mailer', $mailer);
    

Gotchas and Tips

Pitfalls

  1. Bundle Registration:

    • Symfony 4+: Ensure the bundle is listed in config/bundles.php. The AppKernel.php registration method is deprecated.
    • Symfony 3.x: Verify AppKernel.php includes the bundle in the registerBundles() method.
  2. Twig Paths:

    • The bundle expects templates in templates/Mails/ or @DonkeyCodeMail/Mails/. Misconfigured paths will throw TemplateNotFoundException.
    • Fix: Use absolute paths (e.g., @YourBundle/Mails/template.html.twig) for clarity.
  3. SwiftMailer Dependency:

    • The bundle relies on SwiftMailer. If not installed, emails will fail silently or throw ClassNotFoundException.
    • Fix: Install SwiftMailer explicitly:
      composer require symfony/swiftmailer-bundle
      
  4. Configuration Overrides:

    • Default config values (e.g., mail_from) may not persist if not set in config/packages/donkey_code_mail.yaml.
    • Fix: Explicitly define all required options.
  5. Deprecated Methods:

    • The getContainer() method is outdated. Use dependency injection (e.g., constructor injection) instead:
      public function __construct(private Mailer $mailer) {}
      

Debugging

  1. Email Not Sending:

    • Check SwiftMailer’s transport configuration (e.g., mailer_transport in .env).
    • Enable SwiftMailer logging:
      # config/packages/swiftmailer.yaml
      swiftmailer:
          logging: true
      
  2. Twig Errors:

    • Ensure all blocks (subject, body, title, content) are defined in your template. Missing blocks may cause silent failures.
    • Use {{ dump(_context) }} in Twig to inspect variables.
  3. Styling Issues:

    • The bundle’s default CSS may conflict with your templates. Override the layout’s styles:
      {% block styles %}
          {{ parent() }}
          <style>
              /* Your custom styles */
          </style>
      {% endblock %}
      

Tips

  1. Custom Layouts: Override the default layout to match your brand:

    {# templates/Mails/layout.html.twig #}
    {% extends "@DonkeyCodeMail/Mails/layout.html.twig" %}
    {% block header %}
        <div style="background: {{ config('donkey_code_mail.options.header_bg') }}">
            <img src="{{ asset('images/logo.png') }}" alt="Logo">
        </div>
    {% endblock %}
    
  2. Environment-Specific Config: Use Symfony’s parameter bag for environment-specific settings:

    # config/packages/donkey_code_mail.yaml
    donkey_code_mail:
        mail_from: '%env(MAIL_FROM)%'
    
  3. Performance:

    • Cache Twig templates for better performance:
      twig:
          cache: '%kernel.cache_dir%/twig'
      
    • Pre-compile templates in production.
  4. Extensions:

    • Extend the Mailer class to add custom methods:
      // src/Service/CustomMailer.php
      class CustomMailer extends \DonkeyCode\MailBundle\Mailer
      {
          public function sendNewsletter(array $recipients, array $data)
          {
              foreach ($recipients as $email) {
                  $this->createMessage()
                      ->setTemplate('Mails/newsletter.html.twig', $data)
                      ->setTo($email)
                      ->send();
              }
          }
      }
      
      Register it as a service:
      services:
          App\Service\CustomMailer:
              parent: donkeycode.mailer
      
  5. Local Testing: Use a local SMTP server (e.g., MailHog) for testing:

    # .env
    MAILER_TRANSPORT=smtp
    MAILER_HOST=mailhog
    MAILER_PORT=1025
    
  6. Fallback for Missing Config: Handle cases where mail_from or reply_to are null:

    $mailer->createMessage()
        ->setFrom($this->getParameter('default_mail_from') ?? 'no-reply@example.com')
        ->setTemplate(...)
        ->send();
    
  7. Security:

    • Sanitize Twig variables to prevent XSS:
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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