2015-07-11 200 views
0

我正在使用PHPMailer發送郵件,但它來自我的本地主機xampp。當我在Postman中測試我的API時,處理請求花費的時間太長,但呈現響應狀態200,但沒有返回JSON響應。以下是我的代碼。響應狀態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 = '[email protected]';       
    $mail->Password = '****';       
    $mail->SMTPSecure = 'ssl';     
    $mail->WordWrap = 50;  
    $mail->IsHTML(true); 

    $mail->SetFrom('[email protected]'); 
    $mail->AddReplyTo($headers); 
    $mail->Subject = $subject; 
    $mail->MsgHTML($body); 
    $mail->AddAddress($to, ""); 

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

    return true; 
} 

謝謝你的時間。

+0

您能提取後您從郵差得到了HTTP響應? – light

+0

@light,在郵遞員我只是得到一個空的HTML,但在JSON響應它說沒有反應返回。 但答覆狀態是200 –

+0

好的。分析代碼,我認爲這是因爲'die()'簡單地終止了PHP腳本,因此Web服務器返回一個「200」表示成功,因爲您的PHP腳本沒有設置標頭。現在,問題是:郵件爲什麼失敗。你在運行什麼操作系統? – light

回答

0

您需要隔離測試您的郵件發送代碼 - 錯誤隱藏在您的其他代碼後面。長時間延遲很可能意味着您的網絡超時,或者由於連接不良或DNS超時。嘗試設置$mail->SMTPDebug = 3;,以便您可以看到連接錯誤。檢查PHPMailer troubleshooting guide

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); 
} 
相關問題