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

Mailjet Bundle Laravel Package

antilop/mailjet-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require antilop/mailjet-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Antilop\Bundle\MailjetBundle\MailjetBundle::class => ['all' => true],
    ];
    
  2. Configure Mailjet Add mailjet.yml to config/packages/ (Symfony 5+) or config/ (older):

    mailjet:
        client:
            api_key: '%env(MAILJET_API_KEY)%'
            api_secret_key: '%env(MAILJET_API_SECRET)%'
        templates:
            welcome_email:
                id: '12345'
                from_email: 'noreply@example.com'
                from_name: 'Example App'
    
  3. First Use Case: Send a Template Email Inject the MailjetMailer service and use it in a controller/service:

    use Antilop\Bundle\MailjetBundle\Mailer\MailjetMailer;
    
    class UserController
    {
        public function __construct(private MailjetMailer $mailjetMailer) {}
    
        public function sendWelcomeEmail(User $user)
        {
            $this->mailjetMailer->sendTemplate(
                'welcome_email', // Template name from config
                $user->email,
                ['name' => $user->name] // Template variables
            );
        }
    }
    

Implementation Patterns

Core Workflows

  1. Sending Emails

    • Templates: Use predefined templates from mailjet.yml for structured emails:
      $mailer->sendTemplate('template_name', 'recipient@example.com', ['var1' => 'value']);
      
    • Raw Emails: Send plain HTML/text emails without templates:
      $mailer->sendEmail(
          'subject',
          'recipient@example.com',
          'html_content',
          'text_content'
      );
      
  2. Dynamic Templates Override template configurations dynamically (e.g., per environment):

    # config/packages/mailjet_dev.yml (for dev)
    mailjet:
        templates:
            welcome_email:
                from_email: 'dev-team@example.com'
    
  3. Event Listeners Trigger emails from domain events (e.g., UserRegisteredEvent):

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class EmailSubscriber implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                UserRegisteredEvent::class => 'onUserRegistered',
            ];
        }
    
        public function onUserRegistered(UserRegisteredEvent $event)
        {
            $this->mailjetMailer->sendTemplate('welcome_email', $event->getUser()->email, [...]);
        }
    }
    
  4. Batch Processing Use Symfony’s Messenger component to queue emails for async sending:

    $this->mailjetMailer->sendTemplateAsync('template', 'user@example.com', [...]);
    

Integration Tips

  • Environment Variables: Store MAILJET_API_KEY and MAILJET_API_SECRET in .env.
  • Testing: Mock MailjetMailer in PHPUnit:
    $this->mailjetMailer = $this->createMock(MailjetMailer::class);
    $this->mailjetMailer->expects($this->once())
        ->method('sendTemplate')
        ->with('welcome_email', 'test@example.com', ['name' => 'Test']);
    
  • Logging: Enable Monolog to debug API calls:
    # config/packages/monolog.yaml
    handlers:
        mailjet:
            type: stream
            path: "%kernel.logs_dir%/mailjet.log"
            level: debug
    

Gotchas and Tips

Pitfalls

  1. Template IDs

    • Hardcoded template IDs in mailjet.yml may break if Mailjet template IDs change. Use environment variables or a database-backed solution for production.
  2. API Rate Limits

    • Mailjet enforces rate limits. Handle Mailjet\Client\Exception\ApiException gracefully:
      try {
          $mailer->sendTemplate(...);
      } catch (ApiException $e) {
          $this->logger->error('Mailjet API error: ' . $e->getMessage());
          // Retry or notify admin
      }
      
  3. Configuration Overrides

    • The bundle does not support runtime template overrides. Predefine all templates in mailjet.yml.
  4. Deprecated Methods

    • The mailjet-apiv3-php library (v1.5) is outdated. Monitor for breaking changes if upgrading.

Debugging

  1. Enable Verbose Logging Add to mailjet.yml:

    client:
        debug: true
    

    Logs will appear in var/log/dev.log.

  2. Validate API Keys Test connectivity early:

    $client = $this->mailjetMailer->getClient();
    $client->getContact()->getContact(1); // Trigger a dummy API call
    
  3. Template Variables Ensure template variables match Mailjet’s expected format (e.g., {{var}} syntax). Test templates in the Mailjet UI first.


Extension Points

  1. Custom Mailer Extend MailjetMailer for additional features:

    class CustomMailjetMailer extends MailjetMailer
    {
        public function sendTransactional(string $template, string $to, array $vars)
        {
            // Add logic for transactional emails
        }
    }
    

    Register as a service in config/services.yaml:

    services:
        App\Mailer\CustomMailjetMailer:
            decorates: 'antilop.mailjet.mailer'
            arguments: ['@.inner']
    
  2. Event Dispatching Dispatch custom events after sending:

    $mailer->sendTemplate(..., [
        'onSend' => function (EmailSentEvent $event) {
            $this->eventDispatcher->dispatch($event);
        }
    ]);
    
  3. Template Repository Replace the static mailjet.yml with a dynamic repository (e.g., Doctrine):

    // Override MailjetBundle's template loader
    services:
        antilop.mailjet.template_loader:
            class: App\Mailjet\DynamicTemplateLoader
            arguments: ['@doctrine.orm.entity_manager']
    
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle