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

apacz/mail-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require apacz/mail-bundle
    

    Add to AppKernel.php (Symfony 3.3):

    new Apacz\MailBundle\ApaczMailBundle(),
    
  2. Configuration Define mail settings in config/packages/apacz_mail.yaml:

    apacz_mail:
        from_email: '[email protected]'
        from_name: 'Your App'
        transport: '%env(MAILER_DSN)%' # e.g., 'smtp://user:[email protected]:587'
    
  3. First Use Case Send a basic email via a Service:

    use Apacz\MailBundle\Mailer\MailerService;
    
    class UserMailer {
        private $mailer;
    
        public function __construct(MailerService $mailer) {
            $this->mailer = $mailer;
        }
    
        public function sendWelcomeEmail($to, $name) {
            $this->mailer->send(
                'emails/welcome.twig', // Twig template
                ['name' => $name],      // Data
                $to,
                'Welcome to Our App'    // Subject
            );
        }
    }
    

Implementation Patterns

Core Workflows

  1. Twig Templates

    • Store templates in templates/emails/ (e.g., welcome.twig).
    • Access via $mailer->send('emails/welcome.twig', $data).
    • Tip: Use {{ app.name }} for dynamic app context.
  2. Attachments

    $this->mailer->send(
        'emails/invoice.twig',
        ['total' => 99.99],
        '[email protected]',
        'Your Invoice',
        ['attachments' => ['/path/to/invoice.pdf']]
    );
    
  3. Async Sending (Queue)

    • Publish an event (MailSentEvent) and listen for it:
    // Event subscriber
    public function onMailSent(MailSentEvent $event) {
        $this->dispatcher->dispatch(new SendMailJob($event->getMessage()));
    }
    
  4. Dynamic Recipients

    $recipients = ['[email protected]', '[email protected]'];
    $this->mailer->sendToMultiple(
        'emails/newsletter.twig',
        ['content' => 'Hello!'],
        $recipients,
        'Monthly Newsletter'
    );
    

Integration Tips

  • Symfony Forms: Bind email fields to Apacz\MailBundle\Form\Type\EmailType.
  • Validation: Use Apacz\MailBundle\Validator\Constraints\ValidEmail for custom rules.
  • Testing: Mock MailerService in PHPUnit:
    $mailer = $this->createMock(MailerService::class);
    $mailer->expects($this->once())->method('send');
    

Gotchas and Tips

Pitfalls

  1. Template Paths

    • Error: TemplateNotFoundException if emails/ is missing or misconfigured.
    • Fix: Verify twig.paths in config/packages/twig.yaml includes templates/.
  2. Transport Configuration

    • Error: Emails fail silently if transport is invalid.
    • Fix: Log MailerService exceptions:
      try {
          $this->mailer->send(...);
      } catch (\Swift_TransportException $e) {
          \Log::error('Mail transport error: ' . $e->getMessage());
      }
      
  3. Character Encoding

    • Issue: Non-ASCII subjects/body may corrupt.
    • Fix: Explicitly set charset in config/packages/apacz_mail.yaml:
      apacz_mail:
          charset: 'UTF-8'
      

Debugging

  • Enable SwiftMailer Debug:

    # config/packages/swiftmailer.yaml
    swiftmailer:
        debug: '%kernel.debug%'
    

    Check logs for raw email content in var/log/dev.log.

  • Inspect Sent Emails: Use Symfony’s SwiftMailer\Transport\NullTransport for testing:

    apacz_mail:
        transport: 'null://localhost' # Discards emails
    

Extension Points

  1. Custom Mailers Extend Apacz\MailBundle\Mailer\AbstractMailer for domain-specific logic:

    class CustomMailer extends AbstractMailer {
        protected function getDefaultFrom() {
            return '[email protected]';
        }
    }
    
  2. Events Listen for mail.sent or mail.failed events to log/analyze:

    // src/EventListener/MailListener.php
    public static function getSubscribedEvents() {
        return [
            'mail.sent' => 'onMailSent',
            'mail.failed' => 'onMailFailed',
        ];
    }
    
  3. Override Templates Use Symfony’s template inheritance to modify default templates (e.g., base_email.html.twig).

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.
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource
noith/settings
kda/laravel-package