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

c975l/email-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Run composer require c975l/email-bundle and enable the bundle in config/bundles.php (Laravel 5.5+) or AppKernel.php (older versions):

    c975L\EmailBundle\c975LEmailBundle::class => ['all' => true],
    
  2. Publish Configuration Publish the default config with:

    php artisan vendor:publish --provider="c975L\EmailBundle\c975LEmailBundle" --tag="config"
    

    This creates config/email_bundle.php. Configure:

    • Database storage (enable store_emails).
    • Mailer transport (Symfony Mailer config).
    • Default sender/recipient roles.
  3. Run Migrations

    php artisan migrate
    

    This creates the emails table for storage.

  4. First Email Use the EmailService in a controller:

    use c975L\EmailBundle\Service\EmailService;
    
    public function sendWelcomeEmail()
    {
        $email = $this->emailService->create()
            ->setSubject('Welcome!')
            ->setTo('user@example.com')
            ->setTemplate('emails/welcome'); // Must exist in resources/views/
        $this->emailService->send($email);
    }
    

Implementation Patterns

Core Workflows

  1. Sending Emails

    • Basic Usage:
      $email = $this->emailService->create()
          ->setSubject('Hello')
          ->setFrom('no-reply@example.com')
          ->setTo(['user1@example.com', 'user2@example.com'])
          ->setTemplate('emails/generic')
          ->addAttachment('/path/to/file.pdf');
      $this->emailService->send($email);
      
    • Dynamic Templates: Pass data to templates via setTemplateData():
      $email->setTemplateData(['name' => 'John']);
      
  2. Storing Emails

    • Enable store_emails: true in config. Emails auto-save to emails table.
    • Retrieve sent emails via repository:
      $sentEmails = $this->emailRepository->findBy(['status' => 'sent']);
      
  3. Admin Dashboard

    • Use the /email route (protected by ROLE_EMAIL_ADMIN).
    • Extend the default Twig template (resources/views/email_bundle/index.html.twig) to customize the UI.
  4. Testing

    • Mock EmailService in tests:
      $emailService = $this->createMock(EmailService::class);
      $emailService->expects($this->once())->method('send');
      $this->app->instance(EmailService::class, $emailService);
      

Integration Tips

  • Queue Emails: Wrap send() in a job for async processing:
    use c975L\EmailBundle\Job\SendEmailJob;
    
    dispatch(new SendEmailJob($email));
    
  • Custom Templates: Override default templates in resources/views/email_bundle/ (e.g., email.html.twig).
  • Events: Listen for email.sent/email.failed events:
    Event::listen('email.sent', function ($email) {
        Log::info("Email sent to {$email->getTo()}");
    });
    

Gotchas and Tips

Pitfalls

  1. Template Paths:

    • Templates must be in resources/views/ (e.g., emails/welcome.html.twig).
    • Debug missing templates with php artisan config:clear if paths aren’t detected.
  2. Role Configuration:

    • Default roles (ROLE_EMAIL_ADMIN, ROLE_EMAIL_USER) may conflict with existing roles. Override in config/email_bundle.php:
      'roles' => [
          'admin' => 'ROLE_CUSTOM_ADMIN',
          'user' => 'ROLE_CUSTOM_USER',
      ],
      
  3. Database Storage:

    • Disabling store_emails permanently deletes the emails table. Backup first if unsure.
    • Large email volumes may bloat the DB. Consider archiving old emails via a cron job.
  4. Attachments:

    • Files must be readable by the web server. Use absolute paths or storage_path():
      $email->addAttachment(storage_path('app/files/report.pdf'));
      

Debugging

  • Logs: Enable debug mode (APP_DEBUG=true) to see Symfony Mailer logs in storage/logs/.
  • Common Errors:
    • TemplateNotFoundException: Verify template paths and run composer dump-autoload.
    • TransportException: Check Symfony Mailer config (e.g., SMTP credentials in .env).

Extension Points

  1. Custom Email Model: Extend the Email entity (e.g., add metadata column):

    // src/Entity/ExtendedEmail.php
    use c975L\EmailBundle\Entity\Email as BaseEmail;
    
    class ExtendedEmail extends BaseEmail {
        /**
         * @ORM\Column(type="json")
         */
        private $metadata;
    }
    

    Update the bundle’s EmailType to include the new field.

  2. Override Services: Bind a custom EmailService in config/services.php:

    c975L\EmailBundle\Service\EmailService::class => \App\Service\CustomEmailService::class,
    
  3. API Endpoints: Use the bundle’s EmailController as a base to add REST endpoints:

    // routes/api.php
    Route::post('/api/emails', [EmailController::class, 'sendApiEmail']);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware