s-ichikawa/laravel-sendgrid-driver
Installation:
composer require s-ichikawa/laravel-sendgrid-driver
Ensure compatibility with your Laravel version (e.g., ^4.0 for Laravel 9/10/11).
Configuration:
Add your SendGrid API key to .env:
SENDGRID_API_KEY=your_api_key_here
Publish the config file (if needed) and update config/mail.php:
'driver' => env('MAIL_DRIVER', 'sendgrid'),
First Use Case:
Send a test email via a Mailable class or Mail::send():
use Illuminate\Support\Facades\Mail;
use App\Mail\TestEmail;
Mail::to('recipient@example.com')->send(new TestEmail());
Sending Emails:
Mail::send(), Mailable classes, or queue() for async sends.Mail::to('user@example.com')
->attach($pathToFile)
->send(new OrderShipped($order));
Templates and Substitutions:
Mail::send([], [], function ($message) {
$message->to('user@example.com')
->subject('Welcome!')
->setBody('Hello, {name}!', 'text/html')
->with([
'name' => 'John Doe',
]);
});
Queueing Emails:
MAIL_QUEUE_CONNECTION in .env (e.g., database, redis) to defer sends:
MAIL_QUEUE_CONNECTION=database
php artisan queue:work
Testing:
MailFake for unit tests:
Mail::fake();
Mail::to('test@example.com')->send(new TestEmail());
Mail::assertSent(TestEmail::class);
Environment-Specific Configs:
Use Laravel’s .env files to switch between sendgrid and other drivers (e.g., log for testing):
MAIL_DRIVER=sendgrid # Production
MAIL_DRIVER=log # Local testing
Customizing Headers:
Add SendGrid-specific headers (e.g., X-SMTPAPI for tracking):
Mail::to('user@example.com')->withSwiftMessage(function ($message) {
$message->getHeaders()->addTextHeader('X-SMTPAPI', json_encode([
'track' => ['opens' => true, 'clicks' => true]
]));
});
Logging and Debugging: Enable SendGrid’s Event Webhook to log email events in your app:
// In a controller or service
$webhookUrl = route('sendgrid.webhook');
// Configure webhook in SendGrid dashboard
API Key Security:
.env or hardcode API keys. Use Laravel’s .env or a secrets manager.Rate Limits:
try {
Mail::send(...);
} catch (Exception $e) {
if ($e->getCode() === 429) {
sleep(10); // Retry after 10 seconds
Mail::send(...);
}
}
Attachment Size Limits:
Mail::to('user@example.com')->attach('https://cdn.example.com/large-file.pdf');
Queue Stuck Emails:
database queue).storage/logs/laravel.log).Enable SendGrid Debug Mode:
Add this to your .env to log API responses:
SENDGRID_DEBUG=true
Check logs in storage/logs/laravel.log for raw API calls/responses.
Validate API Key: Test connectivity with a simple API call:
curl -X GET "https://api.sendgrid.com/v3/user/ip" -H "Authorization: Bearer $SENDGRID_API_KEY"
Common Errors:
401 Unauthorized: Invalid API key or permissions.400 Bad Request: Invalid email format or missing required fields (e.g., to).500 Internal Server Error: Check SendGrid’s API error codes.Custom SendGrid Client:
Override the default SendGrid client by binding a custom instance in AppServiceProvider:
use SendGrid\Mail\Mailer;
use SendGrid\Mail\Transport;
public function register()
{
$this->app->singleton(Mailer::class, function ($app) {
$transport = new Transport();
$transport->setApiKey($app['config']['mail.sendgrid.api_key']);
return new Mailer($transport);
});
}
Event Listeners:
Listen to MailSent events to log or process sent emails:
use Illuminate\Mail\Events\MessageSent;
Event::listen(MessageSent::class, function (MessageSent $event) {
logger()->info('Email sent to: ' . $event->message->getTo()[0]['address']);
});
Dynamic Templates: Fetch SendGrid templates dynamically at runtime:
use SendGrid\Mail\Template;
$template = Template::getInstance()
->setTemplateId('your_template_id')
->setVersion('1.0');
Webhook Handling: Create a route to handle SendGrid event webhooks:
Route::post('/sendgrid/webhook', function (Request $request) {
$payload = $request->json()->all();
// Process events (e.g., 'processed', 'dropped')
logger()->info('SendGrid event:', $payload);
});
How can I help you explore Laravel packages today?