Search code examples
phpemaildelay

How to delay PHP email using sleep


I'm using a php script to send an email that I want to send after a time delay. I am going to use sleep() for that. But where would I put that to delay the email from sending? Here's my code:

<?php    
if(isset($_POST['email']))
{

 $headers = "From: Memory Jet <[email protected]>\r\n";


$to_visitor = $_POST["email"];
$common_data = $_POST["message"];
//I originally put the delay here, it didn't work
mail($to_visitor, "Your Memory", $common_data, $headers);

} ?>

Thanks in advance! =) -Ben


Solution

  • Two questions: 1) What do you mean by "it didn't work"; what did it do? 2) Why do you want to wait a long time before sending the email?

    Also, I would highly recommend against calling sleep() in your PHP scripts, as it will delay completion of the script, and thus, the HTML to the browser.

    I would implement a more robust Email queuing system. Basically, instead of sending the email in the script, you insert a row into a database, which contains a queue of emails to be sent. Then, you have a cron or other background process, that periodically checks the database for emails to be sent, and then sends them in a batch.

    Additionally, you could specify a "to-be-sent time" in the table, and the sender script would not send any emails until the current time is after that "to-be-sent time".

    The problem with sleep()ing is that the PHP script fires up, executes, then is gone. In order to do something in the (relatively) distant future, you need something else. cron was just an example. You could use something in windows task scheduler (you didn't mention target platform), or write your own program. It wouldn't be a whole lot of work to write something in C (or maybe even PHP) that runs continually, checking the database and sending emails).