Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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":"[email protected]"
                     }
                  ],
                  "subject":"Hello World from the SendGrid PHP Library!"

               }
            ],
            "from":{
               "email":"[email protected]"
            },
            "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.

like image 693
Karan Avatar asked Oct 30 '22 20:10

Karan


1 Answers

This works perfectly and is much simpler than the solutions already posted:

$email = new \SendGrid\Mail\Mail();
$email->setFrom( "[email protected]", "Some guy" );
$email->addTo( "[email protected]", "Another guy" );
$email->setTemplateId(
    new \SendGrid\Mail\TemplateId( TEMPLATE_ID )
);

// === Here comes the dynamic template data! ===
$email->addDynamicTemplateDatas( [
    'variable1'     => 'Some stuff',
    'templatesRock' => 'They sure do!'
] );

$sendgrid = new \SendGrid( API_KEY );
$response = $sendgrid->send( $email );
like image 108
Alan Grainger Avatar answered Nov 15 '22 06:11

Alan Grainger