Closed3
SendGrid PHP API
$ composer require sendgrid/sendgrid
<?php
namespace App\Controllers;
use Exception;
use SendGrid;
use SendGrid\Mail\Mail;
use SendGrid\Mail\Personalization;
use SendGrid\Mail\To;
class SendGridController extends BaseController
{
private const API_KEY = '';
private const TEMPLATE_ID = '';
public function send()
{
$email = new Mail();
try {
$email->setFrom('from@example.com', 'From Name');
$email->setTemplateId(self::TEMPLATE_ID);
$email->addTo('to@example.com');
$email->addDynamicTemplateData('value1', 'foo');
$email->addDynamicTemplateData('value2', 'bar');
$email->addDynamicTemplateData('value3', 'baz');
} catch (SendGrid\Mail\TypeException $e) {
die('Caught exception: ' . $e->getMessage());
}
$sendgrid = new SendGrid(self::API_KEY);
try {
$response = $sendgrid->send($email);
echo "<pre>";
echo $response->statusCode() . "\n";
print_r($response->headers());
echo $response->body() . "\n";
echo "</pre>";
} catch (Exception $e) {
die('Caught exception: ' . $e->getMessage());
}
}
public function bulkSend()
{
$email = new Mail();
try {
$email->setFrom('from@example.com', 'From Name');
$email->setTemplateId(self::TEMPLATE_ID);
$users = [
[
'email_address' => 'to1@example.com',
'value1' => 'foo1',
'value2' => 'foo2',
'value3' => 'foo3',
],
[
'email_address' => 'to2@example.com',
'value1' => 'bar1',
'value2' => 'bar2',
'value3' => 'bar3',
],
[
'email_address' => 'to3@example.com',
'value1' => 'baz1',
'value2' => 'baz2',
'value3' => 'baz3',
],
];
foreach ($users as $user) {
$personalization = new Personalization();
$personalization->addTo(new To($user['email_address']));
$personalization->addDynamicTemplateData('value1', $user['value1']);
$personalization->addDynamicTemplateData('value2', $user['value2']);
$personalization->addDynamicTemplateData('value3', $user['value3']);
$email->addPersonalization($personalization);
}
} catch (SendGrid\Mail\TypeException $e) {
die('Caught exception: ' . $e->getMessage());
}
$sendgrid = new SendGrid(self::API_KEY);
try {
$response = $sendgrid->send($email);
echo "<pre>";
echo $response->statusCode() . "\n";
print_r($response->headers());
echo $response->body() . "\n";
echo "</pre>";
} catch (Exception $e) {
die('Caught exception: ' . $e->getMessage());
}
}
}
このスクラップは2024/02/21にクローズされました