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

标签 php email sendgrid

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

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

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

这是代码

$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();

请帮忙。

最佳答案

这完美地工作并且比已经发布的解决方案简单得多:

$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 );

关于php - 如何将动态数据传递给sendgrid的电子邮件模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39466974/

相关文章:

ruby-on-rails - Ruby on Rails : bad username/password?(535 验证失败)

php - 使用 PHP 通过 sendgrid 发送邮件时获取响应

php - 在 PHP 中实例化类的正确方法

python - django更改电子邮件地址-确认密码

php - 使用 PHP 和 JavaScript 上传文件

android - 从邮件附件打开 x509 证书 (.crt) 时接收 Intent

php - 电子邮件的动态图像,例如倒计时时钟(根据 gmail 图像缓存)

.net - 如何使用 sendgrid 电子邮件发送嵌入的图像?

php - 修改后的可重用查询?

php - undefined variable : data (View: C:\cygwin64\home\hp\AddressBook\resources\views\Update\edit.blade.php)