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

Email Bundle Laravel Package

austral/email-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   Add the bundle via Composer:
   ```bash
   composer require austral/email-bundle

Register the bundle in config/bundles.php:

Austral\EmailBundle\AustralEmailBundle::class => ['all' => true],
  1. Configuration Publish the default config:

    php artisan vendor:publish --tag=email-bundle-config
    

    Update config/austral_email.php with your email settings (SMTP, Mailgun, etc.).

  2. First Use Case: Sending a Template Email Define a template in resources/views/emails/welcome.blade.php:

    <h1>Welcome, {{ $name }}!</h1>
    <p>Your account has been created.</p>
    

    Send the email in a controller:

    use Austral\EmailBundle\Service\EmailService;
    
    public function sendWelcomeEmail(EmailService $emailService)
    {
        $emailService->send([
            'to' => 'user@example.com',
            'subject' => 'Welcome!',
            'template' => 'emails.welcome',
            'data' => ['name' => 'John Doe'],
        ]);
    }
    
  3. Viewing Sent Emails Access the email log via the admin panel (if configured) or query the email_log table directly:

    $sentEmails = \Austral\EmailBundle\Entity\EmailLog::all();
    

Implementation Patterns

Core Workflows

  1. Template-Based Emails

    • Store reusable email templates in resources/views/emails/.
    • Pass dynamic data via the data array in EmailService::send().
    • Example:
      $emailService->send([
          'to' => ['user1@example.com', 'user2@example.com'],
          'cc' => 'manager@example.com',
          'bcc' => 'archive@example.com',
          'subject' => 'Your Order #{{ $orderId }}',
          'template' => 'emails.order_confirmation',
          'data' => ['orderId' => 12345, 'total' => '$99.99'],
      ]);
      
  2. Email Logging

    • Automatically logs all sent emails to the email_log table (includes to, subject, sent_at, status).
    • Extend the EmailLog entity to add custom fields (e.g., template_name, metadata):
      // In a migration or entity listener
      $emailLog->setTemplate('emails.order_confirmation');
      $emailLog->setMetadata(['order_id' => 12345]);
      
  3. Queueing Emails

    • Use Laravel’s queue system to defer sending:
      $emailService->sendQueued([...]); // Adds to queue:emails
      
    • Process with:
      php artisan queue:work
      
  4. Admin Panel Integration

    • If using Austral’s admin bundle, register the EmailLog entity for CRUD operations:
      # config/austral_admin.yaml
      entities:
          Austral\EmailBundle\Entity\EmailLog: ~
      
  5. Localization

    • Leverage Austral’s entity-translate-bundle for multilingual emails:
      $emailService->send([
          'locale' => 'es', // Override default locale
          'template' => 'emails.welcome',
          'data' => ['name' => 'Juan'],
      ]);
      

Integration Tips

  1. Customizing Email Headers Override default headers in the config:

    // config/austral_email.php
    'headers' => [
        'X-Sender-ID' => env('EMAIL_SENDER_ID'),
        'Reply-To' => 'support@example.com',
    ],
    
  2. Attachments Use Laravel’s Swift_Attachment:

    $emailService->send([
        'to' => 'user@example.com',
        'attachments' => [
            (new \Swift_Attachment(
                file_get_contents(storage_path('app/report.pdf')),
                'report.pdf',
                'application/pdf'
            ))->setDisposition('attachment'),
        ],
        // ... rest of the config
    ]);
    
  3. Events and Listeners Listen for email events (e.g., EmailSent):

    // In a service provider
    $this->app->booted(function () {
        \Austral\EmailBundle\Event\EmailSent::addListener(function ($event) {
            // Log analytics or trigger side effects
        });
    });
    
  4. Testing Mock the EmailService in tests:

    $emailService = $this->createMock(EmailService::class);
    $emailService->expects($this->once())
        ->method('send')
        ->with([
            'to' => 'user@example.com',
            'subject' => 'Test',
        ]);
    $this->app->instance(EmailService::class, $emailService);
    

Gotchas and Tips

Pitfalls

  1. Dependency Conflicts

    • The bundle requires austral/tools-bundle, austral/entity-bundle, and austral/entity-translate-bundle. Ensure these are installed and compatible:
      composer require austral/tools-bundle austral/entity-bundle austral/entity-translate-bundle
      
    • Fix: Check composer.json for version constraints and run composer update.
  2. Template Paths

    • Templates must be in resources/views/emails/ or a subdirectory (e.g., emails/newsletters/welcome.blade.php).
    • Fix: Use dot notation in the template key: 'template' => 'emails.newsletters.welcome'.
  3. Queue Configuration

    • Queued emails use the emails queue by default. Ensure your queue worker is configured to process it:
      php artisan queue:work --queue=emails
      
    • Fix: Add the queue to your QUEUE_CONNECTION in .env if needed.
  4. Logging Overrides

    • The bundle auto-creates the email_log table. If you customize the EmailLog entity, run:
      php artisan doctrine:migrations:diff
      php artisan doctrine:migrations:migrate
      
    • Fix: Manually create the table or extend the migration.
  5. Symfony Mailer vs. Swiftmailer

    • The bundle uses Symfony Mailer under the hood. If you’re using Laravel’s Mail facade, ensure consistency in configuration (e.g., transport settings).

Debugging Tips

  1. Check Logs

    • Enable debug mode (APP_DEBUG=true) to see email-sending errors in storage/logs/laravel.log.
    • Look for Swift_TransportException or Symfony\Component\Mailer\Exception\TransportException.
  2. Validate Email Data

    • Use dd() to inspect the email data before sending:
      $emailData = [
          'to' => 'user@example.com',
          'subject' => 'Test',
          'template' => 'emails.test',
          'data' => ['key' => 'value'],
      ];
      dd($emailData); // Verify structure
      $emailService->send($emailData);
      
  3. Test SMTP Locally

    • Use a local SMTP server (e.g., MailHog) for testing:
      // config/austral_email.php
      'transport' => 'smtp://mailhog:1025',
      
    • Access MailHog at http://localhost:8025.
  4. Clear Cache

    • After config changes, clear the cache:
      php artisan config:clear
      php artisan cache:clear
      

Extension Points

  1. Custom Email Log Fields Extend the EmailLog entity to add fields like campaign_id or user_id:

    // src/Entity/ExtendedEmailLog.php
    namespace App\Entity;
    
    use Austral\EmailBundle\Entity\EmailLog as BaseEmailLog;
    use Doctrine\ORM\Mapping as ORM;
    
    #[ORM\Entity]
    class ExtendedEmailLog extends BaseEmailLog
    {
        #[ORM\Column]
        private ?int $campaignId = null;
    
        // Getters/setters...
    }
    

    Update the bundle’s EmailService to populate these fields.

  2. Dynamic Templates Fetch templates dynamically (e.g., from a database):

    $templateContent = $templateRepository->find($templateId)->getContent();
    $emailService->send([
        'to' => 'user@example.com',
        'subject' => 'Dynamic Email',
        'html' => $templateContent, // Skip view rendering
        'data' => [],
    ]);
    
  3. Email Validation Add validation rules for email data:

    use Austral\Email
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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