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

问题描述 投票:2回答:1

我目前正在处理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(['[email protected]' => 'Alerts'])
        ->setReplyTo('[email protected]')
        ->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>';
    }

}

这里是打印的响应代码

错误!{“ code”:400,“ headers”:[“ HTTP / 1.1 400 Bad Request”,“ Server:nginx”,“ Date:Fri,27 Dec 2019 13:31:27 GMT”,“ Content-Type:application / json”,“内容长度:238”,“连接:保持活动状态”,“访问控制权限来源:https://sendgrid.api-docs.io”,“访问控制权限方法:POST”,“访问控制权限”允许标题:授权,内容类型,代表,x-sg-elas-acl“,”访问控制最大年龄:600“,” X-否-CORS原因:https://sendgrid.com/docs/Classroom/Basics/API/cors.html“ ,“”,“”],“ body”:“ {\” errors \“:[{\” message \“:\”动态模板化\“,\” field \“:\”个性化不能使用替代.0.substitutions \“,\” help \“:\”http://sendgrid.com/docs/API_Reference/Web_API_v3/Mail/errors.html#message.personalizations.substitutions\“}]}”}}

数组([0] =>错误的请求!)

如您所见,它可能不会将替换与动态模板一起使用,但是我将需要替换这些变量以便使用模板的正确性。如何使用代码解决此问题?

php yii2 sendgrid-api-v3
1个回答
0
投票

我不得不删除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;
}
© www.soinside.com 2019 - 2024. All rights reserved.