响应状态200但没有JSON

时间:2015-07-11 15:03:14

标签: php json api rest phpmailer

我正在使用PHPMailer发送邮件,但它来自xampp中的localhost。当我在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;
}

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

在检查邮件回复时使用此功能

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