Recoverable fatal error: Object of class SendGrid\Mail\Mail could not be converted to string

Viewed 607

I am trying to pass a dynamic value using SendGrid's PHP Library. It works when I pass in a string but I add a dynamic value, I get this error Recoverable fatal error: Object of class SendGrid\Mail\Mail could not be converted to string in C:\xampp\htdocs\new\vendor\sendgrid\sendgrid\lib\helper\Assert.php on line 30

This one works

$email = new \SendGrid\Mail\Mail(); 
$email->setFrom("support@example.com", "example");
$email->setSubject("IMPORTANT: Signal failure");
$email->addTo("user@exampl.com", "{$fname}");
$email->addContent("text/plain", "{$message}");
$email->addContent(
    "text/html", "{$message}"
);
$sendgrid = new \SendGrid('APIKEY');
try {
    $response = $sendgrid->send($email);
    print $response->statusCode() . "\n";
    print_r($response->headers());
    print $response->body() . "\n";
} catch (Exception $e) {
    echo 'Caught exception: '. $e->getMessage() ."\n";
}

This one fails

 $email = new \SendGrid\Mail\Mail(); 
    $email->setFrom("support@example.com", "example");
    $email->setSubject("IMPORTANT: Signal failure");
    $email->addTo("{$email}", "{$fname}"); //this line causes the error
    $email->addContent("text/plain", "{$message}");
    $email->addContent(
        "text/html", "{$message}"
    );
    $sendgrid = new \SendGrid('APIKEY');
    try {
        $response = $sendgrid->send($email);
        print $response->statusCode() . "\n";
        print_r($response->headers());
        print $response->body() . "\n";
    } catch (Exception $e) {
        echo 'Caught exception: '. $e->getMessage() ."\n";
    }

Any suggestion would be appreciated Thanks

1 Answers

In the example where it fails, $email is not a string containing an email address. It is an instance of \SendGrid\Mail\Mail().

Calling it as a string won't work, because it looks like \SendGrid\Mail\Mail() does not implement the Stringable interface.

You can prevent accidents like these by using better variable names like

$mailer = new \SendGrid\Mail\Mail();

or

$sendGridMail = new \SendGrid\Mail\Mail();
Related