This documentation provides examples for specific use cases. Please open an issue or make a pull request for any use cases you would like us to document here. Thank you!
For this example, we assume you have created a transactional template. Following is the template content we used for testing.
Template ID (replace with your own):
13b8f94f-bcae-4ec6-b752-70d6cb59f932
Email Subject:
<%subject%>
Template Body:
<html>
<head>
<title></title>
</head>
<body>
Hello -name-,
<br /><br/>
I'm glad you are trying out the template feature!
<br /><br/>
<%body%>
<br /><br/>
I hope you are having a great day in -city- :)
<br /><br/>
</body>
</html>
<?php
// If you are using Composer
require 'vendor/autoload.php';
// If you are not using Composer (recommended)
// require("path/to/sendgrid-php/sendgrid-php.php");
$from = new SendGrid\Email(null, "[email protected]");
$subject = "I'm replacing the subject tag";
$to = new SendGrid\Email(null, "[email protected]");
$content = new SendGrid\Content("text/html", "I'm replacing the <strong>body tag</strong>");
$mail = new SendGrid\Mail($from, $subject, $to, $content);
$mail->personalization[0]->addSubstitution("-name-", "Example User");
$mail->personalization[0]->addSubstitution("-city-", "Denver");
$mail->setTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932");
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
try {
$response = $sg->client->mail()->send()->post($mail);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo $response->statusCode();
echo $response->headers();
echo $response->body();
<?php
// If you are using Composer
require 'vendor/autoload.php';
// If you are not using Composer (recommended)
// require("path/to/sendgrid-php/sendgrid-php.php");
$request_body = json_decode('{
"personalizations": [
{
"to": [
{
"email": "[email protected]"
}
],
"substitutions": {
"-name-": "Example User",
"-city-": "Denver"
},
"subject": "I\'m replacing the subject tag"
}
],
"from": {
"email": "[email protected]"
},
"content": [
{
"type": "text/html",
"value": "I\'m replacing the <strong>body tag</strong>"
}
],
"template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932"
}');
$apiKey = getenv('SENDGRID_API_KEY');
$sg = new \SendGrid($apiKey);
try {
$response = $sg->client->mail()->send()->post($request_body);
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
echo $response->statusCode();
echo $response->body();
echo $response->headers();