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 Apiv3 Php Laravel Package

mailjet/mailjet-apiv3-php

Official Mailjet PHP wrapper for the Mailjet API v3. Send and track transactional emails, manage contacts, lists and templates, handle events, and integrate Mailjet features in PHP apps with simple client setup and HTTP calls.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mailjet/mailjet-apiv3-php
    

    Add to config/services.php:

    'mailjet' => [
        'api_key' => env('MAILJET_API_KEY'),
        'api_secret' => env('MAILJET_API_SECRET'),
        'version' => 'v3.1', // Default, but explicit is better
    ],
    
  2. First Use Case: Sending an Email

    use Mailjet\Client;
    use Mailjet\Resources;
    
    $mj = new Client(env('MAILJET_API_KEY'), env('MAILJET_API_SECRET'), true, ['version' => 'v3.1']);
    $body = [
        'Messages' => [
            [
                'From' => ['Email' => 'sender@example.com', 'Name' => 'Sender'],
                'To' => [['Email' => 'recipient@example.com', 'Name' => 'Recipient']],
                'Subject' => 'Test Email',
                'TextPart' => 'Hello, this is a test email.',
                'HTMLPart' => '<h1>Hello, this is a test email!</h1>',
            ]
        ]
    ];
    
    $response = $mj->post(Resources::$Email, ['body' => $body]);
    
  3. Where to Look First

    • Mailjet API Docs (for payload structure)
    • Mailjet\Resources (for endpoint constants like Resources::$Email)
    • Mailjet\Client (core class for requests)

Implementation Patterns

Common Workflows

1. Email Sending with Dynamic Data

Use Laravel’s Mail facade + Mailjet’s API for templated emails:

// In a Laravel Mailer
public function build($view, $data)
{
    return $this->markdown($view)
        ->with($data)
        ->to($this->recipient);
}

// In a Controller
$mailer = new MailjetMailer($mjClient); // Custom wrapper
$mailer->send(new TestEmail($user));

2. Contact Management

$contact = [
    'Email' => 'user@example.com',
    'Name' => 'John Doe',
    'Properties' => ['age' => 30, 'custom_field' => 'value']
];
$mj->post(Resources::$Contact, ['body' => ['Contacts' => [$contact]]]);

3. Campaign Tracking

Use Resources::$Event to track opens/clicks:

$event = [
    'Event' => 'open',
    'ContactEmail' => 'user@example.com',
    'CampaignId' => 12345,
    'MessageId' => 'abc123'
];
$mj->post(Resources::$Event, ['body' => $event]);

4. Async Processing with Queues

Dispatch a job for non-critical emails:

SendMailjetEmail::dispatch($mjClient, $emailData)
    ->onQueue('mailjet');

Integration Tips

Laravel-Specific

  • Service Provider Binding:

    $this->app->singleton('mailjet', function ($app) {
        return new Client(
            $app['config']['services.mailjet.api_key'],
            $app['config']['services.mailjet.api_secret']
        );
    });
    
  • Mailjet as a Mail Driver: Extend Laravel’s SwiftMailer or use a package like spatie/laravel-mailjet for seamless integration.

Performance

  • Batch Processing: Use Contacts::createList() for bulk contact imports.
  • Rate Limiting: Mailjet allows 300 requests/minute. Cache API responses for read-heavy operations.

Testing

  • Use Mailjet\Client with mock responses in PHPUnit:
    $mock = $this->getMockBuilder(Client::class)
        ->disableOriginalConstructor()
        ->onlyMethods(['post'])
        ->getMock();
    $mock->method('post')->willReturn(new Response(200, [], '{}'));
    

Gotchas and Tips

Pitfalls

  1. API Key Exposure

    • Never hardcode keys. Use Laravel’s .env and config/services.php.
    • Restrict keys to specific IPs in Mailjet’s API settings.
  2. Payload Validation

    • Mailjet rejects malformed JSON. Validate payloads before sending:
      if (!json_validate($body)) {
          throw new \InvalidArgumentException('Invalid JSON payload');
      }
      
  3. Rate Limits

    • Exceeding 300 requests/minute triggers a 429 Too Many Requests. Implement exponential backoff:
      $retryAfter = $response->getHeader('Retry-After');
      sleep($retryAfter);
      
  4. Async Deliverability

    • Emails sent via API may hit spam filters. Use Mailjet’s dedicated IP for critical campaigns.

Debugging

  • Enable Debug Mode:

    $mj = new Client($apiKey, $apiSecret, true, ['debug' => true]);
    

    Logs requests/responses to storage/logs/mailjet.log.

  • Common Errors:

    Error Code Cause Fix
    400 Invalid payload Validate JSON structure
    401 Invalid API key Check .env and Mailjet dashboard
    403 IP not whitelisted Add IP to Mailjet’s API settings
    429 Rate limit exceeded Implement retries with backoff

Extension Points

  1. Custom Responses Extend Mailjet\Client to handle Mailjet-specific responses:

    class CustomMailjetClient extends Client {
        public function sendEmail(array $data) {
            $response = $this->post(Resources::$Email, ['body' => $data]);
            return $this->parseResponse($response);
        }
    
        protected function parseResponse($response) {
            // Custom logic to parse Mailjet's response format
        }
    }
    
  2. Webhooks Use Mailjet’s webhook events to trigger Laravel jobs:

    Route::post('/mailjet/webhook', function (Request $request) {
        $event = $request->json()->all();
        HandleMailjetEvent::dispatch($event);
    });
    
  3. Template Management Dynamically fetch Mailjet templates:

    $templates = $mj->get(Resources::$Template);
    $templateId = $templates['Data'][0]['ID'];
    

Pro Tips

  • Use Contact::getContact to fetch subscriber data before sending:
    $contact = $mj->get(Resources::$Contact, ['id' => $email]);
    
  • Leverage Campaign::sendCampaign for transactional templates:
    $campaign = [
        'Name' => 'Welcome Email',
        'Recipients' => [['Email' => 'user@example.com']],
        'TemplateID' => 12345,
        'TemplateLanguage' => true
    ];
    $mj->post(Resources::$Campaign, ['body' => $campaign]);
    
  • Monitor with Statistics:
    $stats = $mj->get(Resources::$Statistics, [
        'startDate' => '2023-01-01',
        'endDate' => '2023-12-31'
    ]);
    
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