Karan Karan - 2 months ago 47
PHP Question

How to pass dynamic data to email template of sendgrid?

I have integrated sendgrid in Laravel and I managed to send the email template of sendgrid in emails but I am not able to replace the content in the email templates. I am using Sendgrid Web API V3.

I followed the steps given in the below link but it is not replacing the variables in template with my dynamic data.

Link: How to pass dynamic data to email template desgined on sendgrid webapp ? :-| Sendgrid

Here is code

$sg = new \SendGrid('API_KEY');
$request_body = json_decode('{
"personalizations":[
{
"to":[
{
"email":"example@example.com"
}
],
"subject":"Hello World from the SendGrid PHP Library!"

}
],
"from":{
"email":"from@example.com"
},
"content":[
{
"type":"text/html",
"value":"<html><body> -name- </body></html>"
}
],
"sub": {
"-name-": ["Alice"]
},
"template_id":"xxxxxx-xxx-xxxxxxxx"

}');

$mailresponse = $sg->client->mail()->send()->post($request_body);
echo $mailresponse->statusCode();
echo $mailresponse->body();
echo $mailresponse->headers();


Please help.

Answer

I have overcome this issue by using another way. Below is code that is working fine. May be help some one..

//create mail object
 $mail = new \SendGrid\Mail();
//set from 
 $from = new \SendGrid\Email("SENDER NAME", "SENDER EMAIL");
 $mail->setFrom($from);
//set personalization
 $personalization = new \SendGrid\Personalization();
 $to = new \SendGrid\Email("RECEIVER NAME", "RECEIVER EMAIL");
 $personalization->addTo($to);
 $personalization->setSubject("SUBJECT");
//add substitutions (Dynamic value to be change in template)
 $personalization->addSubstitution(':name', "Any"); 

 $mail->addPersonalization($personalization);
 $mail->setTemplateId("TEMPLATE_ID");
//send email
 $sg = new \SendGrid("API_KEY");

 $response = $sg->client->mail()->send()->post($mail);
Comments