Email Newsletter Integration (SendGrid)
SendGrid is one of the leading transactional email providers, owned by Twilio. It provides a powerful API, dynamic templates, and detailed delivery analytics. Optimal for high volumes of transactional emails.
Sending via API v3
// composer require sendgrid/sendgrid
$email = new \SendGrid\Mail\Mail();
$email->setFrom("[email protected]", "My Store");
$email->setSubject("Order #{$orderId} Confirmed");
$email->addTo($to, $userName);
$email->addContent("text/html", $htmlBody);
$sendgrid = new \SendGrid(env('SENDGRID_API_KEY'));
$response = $sendgrid->send($email);
Dynamic Templates
Templates are created in SendGrid UI with variables {{variable_name}}:
$email->setTemplateId(env('SENDGRID_ORDER_TEMPLATE_ID'));
$email->addDynamicTemplateDatas([
'order_id' => $orderId,
'order_total' => $orderTotal,
'items' => $itemsArray,
'customer' => ['name' => $name, 'address' => $address]
]);
Managing Subscribers (Marketing API)
// Add contact to list
Http::withToken(env('SENDGRID_API_KEY'))
->put('https://api.sendgrid.com/v3/marketing/contacts', [
'list_ids' => [env('SENDGRID_LIST_ID')],
'contacts' => [[
'email' => $email,
'first_name' => $firstName,
'custom_fields' => ['e1_T' => 'customer'] // custom field
]]
]);
Event Webhook for Tracking
SendGrid can send events (delivered, opened, click, bounce) to your site's webhook:
Route::post('/webhooks/sendgrid', function (Request $request) {
foreach ($request->json()->all() as $event) {
EmailEvent::create([
'email' => $event['email'],
'event' => $event['event'], // 'delivered', 'open', 'click', 'bounce'
'sg_event_id' => $event['sg_event_id']
]);
}
return response('OK');
});
Laravel Mail Integration
In Laravel, SendGrid is connected via the official driver or as SMTP:
MAIL_MAILER=sendgrid
SENDGRID_API_KEY=SG.xxxx
Integration timeline: 1 business day.







