Search code examples
phpyii2sendgrid-api-v3

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


I am currently working on a yii2 application and I have integrated wadeshuler/yii2-sendgrid plugin in my application to send emails through it.

I have setup a dynamic template with a template id in my sendgrid account. Here is the code I am using to test sendgrid integration with my app.

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>';
    }

}

Here is the response code printed

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! )

As you can see it says that substitutions may not be used with dynamic templating, but I will be needing to substitute these variable inorder to use templates correclty. How to fix this using the code?


Solution

  • I had to remove wadeshuler/yii2-sendgrid plugin as it didn't support the latest features and updates in the sendgrid liberary. I installed the latest sendgrid plugin. I also made a component named SendGridManager to route all the emails through it in my application.

    Here is my function inside the component 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;
    }