Search code examples
phpangularemailhttpclient

No response on httpclient .post() method


I've got Angular2+ app which uses PHP as a server-side. I need to send a data to a PHP script, it will proceed the data and create a file, then it will send this file to administrator's mail and give a response to Front-end that message was sent(or an error in another case). So here are some pieces of my code: Angular2+

submit() {
    this.http.post('https://myWeb.site/script.php', this.dataService.sharedData)
.subscribe(response => {
      if (response == "Message sent!"){
          //Do something
         }
     })
}

PHP

header("Access-Control-Allow-Origin: *");

header("Access-Control-Allow-Headers: Content-Type, origin");

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

$vars = get_angular_request_payload();

function get_angular_request_payload() {
   return json_decode(file_get_contents('php://input'), true);
}

//(some data processing and .xlsx file configuration)


$writer = new Xlsx($spreadsheet);
$fileName = 'NewOrder.xlsx';
$writer->save($fileName);


$mail = new PHPMailer();
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tsl';
$mail->SMTPAuth = true;
$mail->Username = "[email protected]";
$mail->Password = "somepassword";
$mail->setFrom('[email protected]', 'sale.some.com');
$mail->addAddress('[email protected]', 'CompanyName');
$mail->Subject = 'New order';
$mail->Body = 'My Text';
$mail->CharSet = 'UTF-8';
$file_to_attach = './NewOrder.xlsx';
$mail->AddAttachment( $file_to_attach , 'New.xlsx' );
$mail->send();

echo json_encode('Message sent!', true);//response

The problem is that sometimes it sends a mail to the administrator, but angular doesn't get any response, and sometimes it works just fine. I've tried to move a response on the 1st line(just to check if it will work), but it doesn't help.

Maybe someone has any suggestions?


Solution

  • After some further investigation, I have finally found out what was the problem. For some reason, Mozilla Firefox doesn't receive a response at all, but Chrome was able to get response data after ~2 min. So the reason was that code which sends mails was not optimized for hosting, as my hosting(as well as many others) doesn't support IPv6 for sending emails it was difficult for it to send a mail that I wanted to. To fix this issue we just need to replace this line of code:

    $mail->Host = 'smtp.gmail.com';
    

    with this:

    $mail->Host = gethostbyname("smtp.gmail.com");
    $mail->SMTPOptions = array('ssl' => array('verify_peer_name' => false));
    

    Now it will use IPv4 for sending emails, this replacement changes execution time from ~2min. to 5sek. and now everything is working just fine.