使用 wadeshuler/yii2-sendgrid 发送 sendgrid 电子邮件时出现错误请求错误

Bad Request Error while sending sendgrid email using wadeshuler/yii2-sendgrid

我目前正在开发一个 yii2 应用程序,我在我的应用程序中集成了 wadeshuler/yii2-sendgrid 插件以通过它发送电子邮件。

我在我的 sendgrid 帐户中设置了一个带有模板 ID 的动态模板。这是我用来测试 sendgrid 与我的应用程序集成的代码。

public function actionTest()
{
    $mailer = Yii::$app->mailer;
    $message = $mailer->compose()
        ->setTo('umair@****.com')      // or just $user->email
        ->setFrom(['alerts@example.com' => 'Alerts'])
        ->setReplyTo('noreply@example.com')
        ->setSubject('Hey -username-, Read This Email')
        ->setHtmlBody('Dear -username-,<br><br>My HTML message here')
        ->setTextBody('Dear -username-,\n\nMy Text message here')
        ->setTemplateId('******')

        ->addSubstitution('-username-', 'Umair Ashraf')
        ->send();

    if ($message === true) {
        echo 'Success!';
        echo '<pre>' . print_r($mailer->getRawResponses(), true) . '</pre>';
    } else {
        echo 'Error!<br>';
        echo '<pre>' . print_r($mailer, true) . '</pre>';
        echo '<pre>' . print_r($mailer->getErrors(), true) . '</pre>';
    }

}

这是打印的响应代码

Error! {"code":400,"headers":["HTTP/1.1 400 Bad Request","Server: nginx","Date: Fri, 27 Dec 2019 13:31:27 GMT","Content-Type: application/json","Content-Length: 238","Connection: keep-alive","Access-Control-Allow-Origin: https://sendgrid.api-docs.io","Access-Control-Allow-Methods: POST","Access-Control-Allow-Headers: Authorization, Content-Type, On-behalf-of, x-sg-elas-acl","Access-Control-Max-Age: 600","X-No-CORS-Reason: https://sendgrid.com/docs/Classroom/Basics/API/cors.html","",""],"body":"{\"errors\":[{\"message\":\"Substitutions may not be used with dynamic templating\",\"field\":\"personalizations.0.substitutions\",\"help\":\"http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.substitutions\"}]}"}

Array ( [0] => Bad Request! )

如您所见,动态模板不能使用替换,但我需要替换这些变量才能正确使用模板。如何使用代码解决此问题?

我不得不删除 wadeshuler/yii2-sendgrid 插件,因为它不支持 sendgrid 库中的最新功能和更新。我安装了最新的 sendgrid 插件。我还制作了一个名为 SendGridManager 的组件,用于在我的应用程序中通过它路由所有电子邮件。

这是我在组件 SendgridManager 中的函数

public function email($from , $to, $substitution, $templateId, $senderName = NULL, 
$toName = NULL, $attachment = NULL)
{
    $response = '';
    $email = new \SendGrid\Mail\Mail();
    $email->setFrom($from,$senderName);
    $email->addTo($to , $toName, $substitution);
    $email->setTemplateId($templateId);
    if(!empty($attachment))
    {
        $email->addAttachment(
            $attachment
        );
    }
    $sendgrid = new \SendGrid($this->apiKey);

    try {
        $response = $sendgrid->send($email);

    } catch (Exception $e) {
        echo 'Caught exception: '.  $e->getMessage(). "\n";
    }

    return $response;
}