【问题标题】:Recoverable fatal error: Object of class SendGrid\Mail\Mail could not be converted to string可恢复的致命错误:SendGrid\Mail\Mail 类的对象无法转换为字符串
【发布时间】:2021-03-12 06:16:18
【问题描述】:

我正在尝试使用 SendGrid 的 PHP 库传递一个动态值。当我传入一个字符串但我添加一个动态值时它可以工作,我得到这个错误 可恢复的致命错误:SendGrid\Mail\Mail 类的对象无法在第 30 行的 C:\xampp\htdocs\new\vendor\sendgrid\sendgrid\lib\helper\Assert.php 中转换为字符串

这个有效

$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";
}

这个失败了

 $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";
    }

任何建议将不胜感激 谢谢

【问题讨论】:

  • 因为您使用的是相同的变量名。尝试更改 addTo() 中的变量名称
  • $email->addTo("{$email}", "{$fname}") $email 不是字符串,它是\SendGrid\Mail\Mail() 的实例,似乎没有Stringable 实现。
  • 难以置信,过去 3 天我一直在努力解决这个错误。谢谢,现在可以使用了
  • 更好的变量命名是关键。 $mailer = new \SendGrid\Mail\Mail();$sendGridMail = new \SendGrid\Mail\Mail(); 会好很多。
  • 我会这样做的,谢谢

标签: php sendgrid


【解决方案1】:

在失败的示例中,$email 不是包含电子邮件地址的字符串。它是\SendGrid\Mail\Mail() 的一个实例。

将其作为字符串调用是行不通的,因为看起来\SendGrid\Mail\Mail() 没有实现Stringable interface

您可以通过使用更好的变量名称来防止此类事故,例如

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2015-11-19
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 2013-08-07
    相关资源
    最近更新 更多