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.
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
],
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]);
Where to Look First
Mailjet\Resources (for endpoint constants like Resources::$Email)Mailjet\Client (core class for requests)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));
$contact = [
'Email' => 'user@example.com',
'Name' => 'John Doe',
'Properties' => ['age' => 30, 'custom_field' => 'value']
];
$mj->post(Resources::$Contact, ['body' => ['Contacts' => [$contact]]]);
Use Resources::$Event to track opens/clicks:
$event = [
'Event' => 'open',
'ContactEmail' => 'user@example.com',
'CampaignId' => 12345,
'MessageId' => 'abc123'
];
$mj->post(Resources::$Event, ['body' => $event]);
Dispatch a job for non-critical emails:
SendMailjetEmail::dispatch($mjClient, $emailData)
->onQueue('mailjet');
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.
Contacts::createList() for bulk contact imports.Mailjet\Client with mock responses in PHPUnit:
$mock = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()
->onlyMethods(['post'])
->getMock();
$mock->method('post')->willReturn(new Response(200, [], '{}'));
API Key Exposure
.env and config/services.php.Payload Validation
if (!json_validate($body)) {
throw new \InvalidArgumentException('Invalid JSON payload');
}
Rate Limits
429 Too Many Requests. Implement exponential backoff:
$retryAfter = $response->getHeader('Retry-After');
sleep($retryAfter);
Async Deliverability
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 |
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
}
}
Webhooks Use Mailjet’s webhook events to trigger Laravel jobs:
Route::post('/mailjet/webhook', function (Request $request) {
$event = $request->json()->all();
HandleMailjetEvent::dispatch($event);
});
Template Management Dynamically fetch Mailjet templates:
$templates = $mj->get(Resources::$Template);
$templateId = $templates['Data'][0]['ID'];
Contact::getContact to fetch subscriber data before sending:
$contact = $mj->get(Resources::$Contact, ['id' => $email]);
Campaign::sendCampaign for transactional templates:
$campaign = [
'Name' => 'Welcome Email',
'Recipients' => [['Email' => 'user@example.com']],
'TemplateID' => 12345,
'TemplateLanguage' => true
];
$mj->post(Resources::$Campaign, ['body' => $campaign]);
Statistics:
$stats = $mj->get(Resources::$Statistics, [
'startDate' => '2023-01-01',
'endDate' => '2023-12-31'
]);
How can I help you explore Laravel packages today?