blue-energy/sendinblue-api-bundle
Installation:
composer require sendinblue/sendinblue-api-bundle:2.0.*
Add to AppKernel.php:
new SendinBlue\SendinBlueApiBundle\SendinBlueApiBundle(),
Configure API Key:
In config/packages/sendin_blue_api.yaml (Symfony 4+) or app/config/config.yml (Symfony 2/3):
sendin_blue_api:
api_key: "%env(SENDINBLUE_API_KEY)%" # Use env vars for security
First Use Case: Send a transactional email via a controller:
use SendinBlue\SendinBlueApiBundle\Service\TransactionalEmailService;
class EmailController extends AbstractController
{
public function sendEmail(TransactionalEmailService $emailService)
{
$email = [
'to' => ['john@doe.com'],
'subject' => 'Welcome!',
'htmlContent' => '<h1>Hello!</h1>',
];
$emailService->sendTransactionalEmail($email);
}
}
Transactional Emails:
$emailService = $this->get('sendinblue_api.transactional_email');
$emailService->sendTransactionalEmail([
'to' => ['user@example.com'],
'subject' => 'Your Order Confirmation',
'htmlContent' => '<p>Order #12345</p>',
'templateId' => 123, // Optional: Use a pre-designed template
]);
SMTP Configuration: Use the bundle’s SMTP service for Laravel-like mailers:
# config/packages/sendin_blue_api.yaml
sendin_blue_api:
api_key: "%env(SENDINBLUE_API_KEY)%"
smtp:
enabled: true
host: "smtp.sendinblue.com"
port: 587
Then inject SendinBlue\SendinBlueApiBundle\Service\SmtpService into your mailer.
Contact Management:
$contactService = $this->get('sendinblue_api.contact');
$contactService->createContact([
'email' => 'user@example.com',
'attributes' => ['NAME' => 'John Doe', 'AGE' => 30],
]);
Event Hooks: Subscribe to SendinBlue webhooks (e.g., bounce events) via Symfony’s event dispatcher:
# config/packages/sendin_blue_api.yaml
sendin_blue_api:
webhook:
enabled: true
secret: "%env(SENDINBLUE_WEBHOOK_SECRET)%"
Create a listener:
// src/EventListener/SendinBlueWebhookListener.php
class SendinBlueWebhookListener
{
public function onWebhook(Request $request, EventDispatcherInterface $dispatcher)
{
$data = json_decode($request->getContent(), true);
// Handle bounce, open, etc.
}
}
Batch Operations:
Use the BatchService for bulk contacts/emails:
$batchService = $this->get('sendinblue_api.batch');
$batchService->createBatch([
'contacts' => [
['email' => 'user1@example.com'],
['email' => 'user2@example.com'],
],
'email' => [
'subject' => 'Batch Email',
'htmlContent' => '<p>Hello batch!</p>',
],
]);
Environment Variables:
Store SENDINBLUE_API_KEY and SENDINBLUE_WEBHOOK_SECRET in .env for security.
Example:
SENDINBLUE_API_KEY=your_api_key_here
SENDINBLUE_WEBHOOK_SECRET=your_webhook_secret
Dependency Injection: Prefer constructor injection for services:
public function __construct(
private TransactionalEmailService $emailService,
private ContactService $contactService
) {}
Error Handling:
Wrap API calls in try-catch blocks to handle SendinBlue\SendinBlueApiBundle\Exception\ApiException:
try {
$emailService->sendTransactionalEmail($email);
} catch (ApiException $e) {
$this->addFlash('error', 'Failed to send email: ' . $e->getMessage());
}
Logging:
Enable debug logging in config/packages/monolog.yaml:
handlers:
sendinblue:
type: stream
path: "%kernel.logs_dir%/sendinblue.log"
level: debug
channels: ["sendinblue"]
Deprecated API Version: This bundle uses SendinBlue API V2, which is outdated. Migrate to API V3 for long-term support.
Symfony 4+ Compatibility:
The bundle is not officially tested for Symfony 4/5. Use config/packages/sendin_blue_api.yaml instead of app/config/config.yml.
config/packages/extra.yaml for legacy support.Webhook Verification:
SendinBlue webhooks require a secret for verification. Always validate the X-Signature header:
use SendinBlue\SendinBlueApiBundle\Event\WebhookEvent;
public function onWebhook(WebhookEvent $event)
{
if (!$event->isValid()) {
throw new \RuntimeException('Invalid webhook signature');
}
}
Rate Limiting: SendinBlue enforces rate limits (e.g., 100 emails/hour for free tier). Implement retries with exponential backoff:
use Symfony\Component\Stopwatch\Stopwatch;
$stopwatch = new Stopwatch();
$event = $stopwatch->start('send_email');
try {
$emailService->sendTransactionalEmail($email);
} catch (ApiException $e) {
if ($e->getCode() === 429) { // Too Many Requests
$event->stop();
sleep($event->getDuration() * 2); // Exponential backoff
retry();
}
}
SMTP vs. API: The SMTP service is a wrapper but may not support all API features (e.g., transactional templates). Prefer the API service for advanced use cases.
Enable API Debugging:
Set debug: true in config:
sendin_blue_api:
api_key: "%env(SENDINBLUE_API_KEY)%"
debug: true
Logs will appear in var/log/sendinblue.log.
Test API Key: Validate your API key with a simple test:
$apiService = $this->get('sendinblue_api.api');
$response = $apiService->get('/account');
dump($response); // Should return account details
Webhook Testing: Use SendinBlue’s webhook simulator to test locally. Mock the request in Symfony:
// tests/Functional/WebhookTest.php
public function testWebhook()
{
$client = static::createClient();
$client->request('POST', '/webhook', [
'headers' => ['X-Signature' => 'your_signature'],
'content' => json_encode(['event' => 'bounce']),
]);
$this->assertEquals(200, $client->getResponse()->getStatusCode());
}
Custom Services:
Extend the bundle’s services by overriding them in config/services.yaml:
services:
App\Service\CustomEmailService:
arguments:
$emailService: '@sendinblue_api.transactional_email'
tags: ['sendinblue_api.custom_service']
Event Subscribers:
Listen to SendinBlue events (e.g., sendinblue.api.response) to log or transform responses:
// src/EventSubscriber/SendinBlueSubscriber.php
class SendinBlueSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
'sendinblue.api.response' => 'onApiResponse',
];
}
public function onApiResponse(GetResponseEvent $event)
{
$response = $event->getResponse();
// Modify or log the response
How can I help you explore Laravel packages today?