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

dekalee/mailjet-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dekalee/mailjet-bundle
    

    Register the bundle in config/app.php under providers:

    Dekalee\MailjetBundle\MailjetBundle::class,
    
  2. Configuration: Add Mailjet credentials and base template ID to .env:

    MAILJET_API_KEY=your_api_key
    MAILJET_SECRET_KEY=your_secret_key
    MAILJET_BASE_TEMPLATE_ID=your_template_id
    

    Reference them in config/packages/dekalee_mailjet.yaml:

    dekalee_mailjet:
        api_key: '%env(MAILJET_API_KEY)%'
        secret_key: '%env(MAILJET_SECRET_KEY)%'
        base_template_id: '%env(MAILJET_BASE_TEMPLATE_ID)%'
    
  3. First Use Case: Send a templated email via SwiftMailer:

    use Symfony\Component\Mailer\MailerInterface;
    use Symfony\Component\Mime\Email;
    
    public function sendWelcomeEmail(MailerInterface $mailer)
    {
        $email = (new Email())
            ->from('noreply@example.com')
            ->to('user@example.com')
            ->subject('Welcome!')
            ->html('<p>Hello, welcome to our platform!</p>');
    
        $mailer->send($email);
    }
    

Implementation Patterns

Core Workflows

  1. Templated Emails: Extend Mailjet’s base template by passing variables:

    # config/packages/dekalee_mailjet.yaml
    dekalee_mailjet:
        base_template_id: 12345
        template_variables:
            name: '{{ user.name }}'
            url: '{{ app.url }}'
    

    Override in code:

    $email->getHeaders()->addTextHeader('X-Mailjet-Variables', json_encode([
        'name' => 'John Doe',
        'url' => 'https://example.com'
    ]));
    
  2. Event Listeners: Hook into Mailjet events (e.g., mailjet.send):

    // src/EventListener/MailjetListener.php
    public function onMailjetSend(MailjetEvent $event)
    {
        $event->getEmail()->getHeaders()->addTextHeader('X-Custom-Tag', 'newsletter');
    }
    

    Register in services.yaml:

    services:
        App\EventListener\MailjetListener:
            tags:
                - { name: 'kernel.event_listener', event: 'mailjet.send', method: 'onMailjetSend' }
    
  3. Queue Integration: Use Laravel’s queue system with Mailjet:

    // Dispatch a job
    SendMailjetEmail::dispatch($email)->delay(now()->addMinutes(5));
    

    Job implementation:

    public function handle()
    {
        $mailer->send($this->email);
    }
    

Integration Tips

  • Laravel Mixins: Extend SwiftMailer’s Transport class to add custom logic:

    // app/MailjetTransport.php
    class MailjetTransport extends \Swift_Transport
    {
        public function isStarted() { return true; }
        public function start() { /* Custom logic */ }
    }
    

    Bind in config/mail.php:

    'mailjet' => [
        'transport' => \App\MailjetTransport::class,
    ],
    
  • Testing: Mock Mailjet responses in PHPUnit:

    $mailer = $this->createMock(MailerInterface::class);
    $mailer->expects($this->once())->method('send')->with($email);
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Never commit .env or hardcode keys in config files. Use Laravel’s .env or Symfony’s %env().
    • Restrict Mailjet API keys to specific IPs or use temporary keys for CI/CD.
  2. Template Variables:

    • Mailjet’s X-Mailjet-Variables header must be a JSON string. Invalid JSON will fail silently.
    • Debug with:
      dd($email->getHeaders()->get('X-Mailjet-Variables'));
      
  3. Rate Limits:

    • Mailjet enforces rate limits. Implement retries with exponential backoff:
      try {
          $mailer->send($email);
      } catch (TransportException $e) {
          if ($e->getMessage() === 'Rate limit exceeded') {
              sleep(10); // Retry after 10 seconds
              $mailer->send($email);
          }
      }
      
  4. Base Template Dependencies:

    • If base_template_id is invalid, emails will fail silently. Validate in a service provider:
      public function boot()
      {
          if (!Mailjet::getTemplate(config('dekalee_mailjet.base_template_id'))) {
              throw new \RuntimeException('Invalid Mailjet base template ID');
          }
      }
      

Debugging

  • Enable SwiftMailer Debug:

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

    Check logs for raw Mailjet responses in storage/logs/laravel.log.

  • Mailjet API Logs: Use Mailjet’s transactional email logs to trace failed sends.

Extension Points

  1. Custom Transports: Extend the bundle’s MailjetTransport to support:

    • Webhook callbacks for delivery events.
    • Custom headers (e.g., X-Mailjet-SandboxMode).
  2. Dynamic Templates: Override base_template_id per email:

    $email->getHeaders()->addTextHeader('X-Mailjet-TemplateID', $dynamicTemplateId);
    
  3. Webhook Handling: Create a controller to process Mailjet’s event webhooks:

    // routes/web.php
    Route::post('/mailjet/webhook', [MailjetWebhookController::class, 'handle']);
    
    public function handle(Request $request)
    {
        $event = $request->json()->all();
        // Process event (e.g., 'sent', 'delivered')
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui