我正在用 php 设计 REST API。我正在使用 slim 框架来设计 API。我想发送一个页面来发送电子邮件。这是我发送电子邮件的代码:
$app->get('/sendemail', function () {
require_once "Mail.php";
$from = "Sender <sender@domain.com>";
$to = "Recipient <recipient@anotherDomain.com>";
$subject = "Hi!";
$body = "Hi,\n\nHey Recipient, you done it...";
$host = "my host";
$username = "myuserid";
$password = "password";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo("<p>" . $mail->getMessage() . "</p>");
} else {
echo("<p>Message successfully sent!</p>");
}
?>
});
如果我将其 checkin 我的单独文件,我发送电子邮件的代码就可以正常工作。但是此代码在 API 中不起作用。
这是正在生成的错误:-
请建议我应该怎么做?
最佳答案
Slim 以面向对象的方式处理 PHP 错误。它使用 PHP 标准类 ErrorException
将所有错误转换为异常。
错误有错误级别,例如E_NOTICE
或E_WARNING
。没有异常(exception)。你要么有异常(exception),要么没有。
您正在使用的 PEAR 邮件程序版本引发了轻微的弃用通知。通常它会被隐藏,你不会知道它,但由于它被转换为异常,Slim 会向你显示一个错误。这是一件好事;你的代码不应该有通知。
要解决这个问题,您可以尝试更新您的邮件程序类以避免弃用的功能,或者您可以自己暂时捕获错误:
function ignoringHandler($level, $str, $file='', $line='', $context=array())
{
// Tell PHP that we have "processed" the error
return true;
}
// Change the handler to ours for notices
$slimHandler = set_error_handler('ignoringHandler', E_NOTICE | E_DEPRECATED);
// Your code accessing older library
restore_error_handler();
关于php - 无法使用 PHP 中构建的 REST API 发送电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8104774/