如何将动态数据传递给sendgrid的电子邮件模板?

Kar*_*ran 5 php email sendgrid

我在 Laravel 中集成了 sendgrid 并且我设法在电子邮件中发送了 sendgrid 的电子邮件模板,但我无法替换电子邮件模板中的内容。我正在使用 Sendgrid Web API V3。

我按照下面链接中给出的步骤操作,但它没有用我的动态数据替换模板中的变量。

链接:如何将动态数据传递到在 sendgrid webapp 上设计的电子邮件模板?:-| 发送网格

这是代码

$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();
Run Code Online (Sandbox Code Playgroud)

请帮忙。

Ala*_*ger 5

这非常有效,并且比已经发布的解决方案简单得多:

$email = new \SendGrid\Mail\Mail();
$email->setFrom( "from@example.com", "Some guy" );
$email->addTo( "to@example.com", "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 );
Run Code Online (Sandbox Code Playgroud)


Kar*_*ran 2

我通过使用另一种方法克服了这个问题。下面是运行良好的代码。可能会帮助某人..

//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);
Run Code Online (Sandbox Code Playgroud)