I am trying to send emails using SendGrid email service using Dynamic Templates.
I am using SendGrid version 7.2.
"sendgrid/sendgrid": "^7.2",
Sending emails is working great and I am able to send emails successfully using the below code.
$this->mail->setTemplateId($templateId);
$response = $this->sendGrid->send($this->mail);
if ($response->statusCode() != 202) {
throw new \Exception("Failed to Send Email.");
}
The problem is sometimes the $templateId
can be an invalid or belong to a deleted template.
I looked through the internet for hours and searched the documentation but couldn't find anything.
Is there a way to check if the email template exists before trying to send the email? Or maybe to retrieve a list of active email template ids from SendGrid?
CodePudding user response:
You can use the "Retrieve paged transactional templates" API to get all (dynamic) templates to check if there is one that matches your ID.
<?php
// Uncomment next line if you're not using a dependency loader (such as Composer)
// require_once '<PATH TO>/sendgrid-php.php';
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
$query_params = json_decode('{
"generations": "legacy",
"page_size": 18
}');
try {
$response = $sg->client->templates()->get(null, $query_params);
print $response->statusCode() . "\n";
print_r($response->headers());
print $response->body() . "\n";
} catch (Exception $ex) {
echo 'Caught exception: '. $ex->getMessage();
}
or via cURL
curl -G -X GET https://api.sendgrid.com/v3/templates \
--header "Authorization: Bearer <<YOUR_API_KEY_HERE>>" \
--data-urlencode "generations=dynamic" \
--data-urlencode "page_size=18"