Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay in PHP mail() function

Tags:

php

I have a small ordering taking app which submits the order to a PHP script by ajax. When the PHP script receives the order it places it in a database, sends an 'OK' message back to the client and then sends a confirmation email to the customer and another to me. The problem is that the client is not seeing the 'OK' (which updates the browser display) for about 15 seconds. If I comment out the email sends, no delay.

... write to database
echo "OK";
mail($semail,'Msg Subject',$message, $header, $bounceto);
mail($semail2,'Msg Subject',$mesage, $header, $bounceto);

Message is only a couple of lines.

Questions:

  • why would there be a delay when calling the mail() function?
  • how can I cause the 'OK' message to be sent without waiting for the PHP script to complete? A flush of some sort I'm guessing.
like image 619
David G Avatar asked May 22 '26 04:05

David G


1 Answers

That's because http://php.net/manual/en/function.mail.php returns boolean value for success or failure and your mail server takes time to process email request.

You can implement some kind of MYSQL queue for emails where you would put emails to be sent and check it with background task (for example using CRON to lauch YourMailQueueProcessingScripts.php that will check if there are any emails to send and perform the sending operation - have in mind that you can run CRON once per minute at most and I don't know if 1 minute delay of sending email is acceptable by you)

like image 189
Mark Avatar answered May 24 '26 18:05

Mark