Skip to content
Advertisement

Recoverable fatal error: Object of class SendGridMailMail could not be converted to string

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 SendGridMailMail could not be converted to string in C:xampphtdocsnewvendorsendgridsendgridlibhelperAssert.php on line 30

This one works

$email = new SendGridMailMail(); 
$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 SendGridMailMail(); 
    $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

Advertisement

Answer

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

Calling it as a string won’t work, because it looks like SendGridMailMail() does not implement the Stringable interface.

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

$mailer = new SendGridMailMail();

or

$sendGridMail = new SendGridMailMail();
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement