【问题标题】:Response status 200 but no JSON响应状态 200 但没有 JSON
【发布时间】:2015-09-30 06:00:24
【问题描述】:

我正在使用 PHPMailer 发送邮件,但它来自我在 xampp 中的本地主机。当我在 Postman 中测试我的 API 时,处理请求需要很长时间,但呈现响应状态 200 但没有返回 JSON 响应。以下是我的代码。

    public function actionSendMail() {
    //Getting request from frontend
    $request = file_get_contents('php://input');

    //Decoding input into an array
    $input = json_decode($request, true);

    //Validating request
    if (is_null($input)) {
        $response = json_encode(['error' => 'Bad Input']);
        die($response);

    } else {
        //mail parameters
        $to      = $input['to'];
        $subject = $input['subject'];
        $body    = $input['body'];
        $headers = $input['headers'];

        //Sending mail 
        if($result = $this->sendMail($to, $subject, $body, $headers) === true) {
            $response = json_encode(['success' => true]);
            echo $response;
        } else {
            $response = json_encode(['error' => 'Mail Not Sent']);
            die($response);
        }
    }
}

private function sendMail ($to, $subject, $body, $headers) {
    //Configurating PHP Mailer
    $mail = new PHPMailer();

    $mail->IsSMTP();                                 
    $mail->Host = 'secure.emailsrvr.com';  
    $mail->Port = 995;
    $mail->SMTPAuth = true;                            
    $mail->Username = 'example@example.com';                           
    $mail->Password = '****';                          
    $mail->SMTPSecure = 'ssl';                   
    $mail->WordWrap = 50;      
    $mail->IsHTML(true); 

    $mail->SetFrom('REDACTED@example.com');
    $mail->AddReplyTo($headers);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($to, "");

    if(!$mail->Send())
        return $mail->ErrorInfo;

    return true;
}

感谢您的宝贵时间。

【问题讨论】:

  • 你能提取 Postman 的 HTTP 响应吗?
  • @light,在邮递员中我只是得到一个空的 HTML,但在 JSON 响应中它说没有返回响应。但是响应状态是 200
  • 好的。分析代码,我认为这是因为die() 只是终止了 PHP 脚本,因此网络服务器返回“200”表示成功,因为您的 PHP 脚本没有设置标头。现在,问题是:为什么邮件失败了。你运行的是什么操作系统?
  • 我使用的是 Windows 8,并且我将骰子包含在一个条件中,因此如果它失败,它应该返回错误消息
  • 注意:Windows 默认没有 SMTP 服务器。另外,您是否从您的 API 路由器/处理器/其他任何地方调用 actionSendMail()?也许你可以在函数的各个地方放一些调试返回行,然后观察你使用 postman 得到的结果。

标签: php json api rest phpmailer


【解决方案1】:

您需要单独测试您的邮件发送代码 - 错误隐藏在您的其他代码后面。长时间延迟很可能意味着您遇到网络超时,可能是由于连接不良或 DNS 超时。尝试设置$mail->SMTPDebug = 3;,这样您就可以看到连接错误。检查PHPMailer troubleshooting guide。

【讨论】:

    【解决方案2】:

    在检查邮件回复时使用它

    if($this->sendMail($to, $subject, $body, $headers)) { 
        $response = json_encode(['success' => true]);
        echo $response;
    } 
    else { 
        $response = json_encode(['error' => 'Mail Not Sent']);
        die($response);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      • 2018-12-21
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      相关资源
      最近更新 更多