/    Sign up×
Community /Pin to ProfileBookmark

PHP Auto Mailer

Hi has anyone seen a turorial or know of a place where are can lern how to create a script that will auto send an emai based on a date trigger.

In a mysql table I have dates that pertain to users and i want to send them an email on so many days before the event date.

any help or direction is great.

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@scragarOct 18.2006 — you can't actualy have a PHP file run endlessly, nore can you get it to run at a specific time without a CronJob.
Copy linkTweet thisAlerts:
@pcthugOct 19.2006 — Here you go, it assumes your database date's are stored as a unix timestamp and should not be run more than once or until you read in the relative log file that [FONT=Courier New]All emails sent. Script Finished.[/FONT] or [FONT=Courier New]No emails matching SQL Query criteria found. Script halted.[/FONT] Alternatively if you receive an error message you should delete all data inside the current log file and restart the script after you have fixed the errors.
[code=php]<pre><?php
/*
As we will be replicating a CronJob with just PHP we
will need to remove any max_execution times that are
enforced upon the script. This is done by setting an
infinite (0) time limit through the set_time_limt()
function.
*/
set_time_limit(0);

/*
Now, unless the user whom executed this script is
going to leave there browser window open whilst this
script is running, we will need to ignore abortion
of the script. This is done by telling the script
that it should ignore user_abortion via the
ignore_user_abort() function.
*/
ignore_user_abort(true);

/*
The log file variable holds the location of the log
file.
*/
$log_file = dirname(__FILE__) . '/my_log.log';

/*
The use log variable ($use_log) sets wheter or not
to log messages to our log file (via our logMsg
function). The default value is true, if you are
experiencing any error messages that start with
logMsg(): you can instantly silence them and force
continuation of the script by setting the
use log variable to false. Please Note: if the
use log variable is set to false, no log of
messages will exsist and therefore you will not be
able to recall how many emails the script has sent.
*/
$use_log = true;

/*
Now if the user is going to close there browser
the best way to inform them on how the script is
running is via a log. We will create a function
(logMsg()) that opens up our log file (my_log.log)
then add our msg to our log file on a new line and
then finally close our window. For maximum
scalability we will allow for the same message to be
sent to the browser via the browser_output
argument.
*/
function logMsg($msg, $browser_output = false)
{
global $log_file, $use_log;

$msg .= "n";

if($use_log)
{
if (!$h = fopen($log_file, 'a'))
{
trigger_error("logMsg(): Cannot open log file ($log_file)", E_USER_ERROR);
return;
}

if (fwrite($handle, $somecontent) === FALSE) {
trigger_error("logMsg(): Cannot write to log file ($log_file)", E_USER_ERROR);
return;
}

fclose($handle);
}

if($browser_output)
{
echo $msg;
}
}

/*
Before we get into database interaction we will test
if our log file is accessable. If not an error message
will be utput to the browser
*/
log_msg('Testing...');

/*
For later use in our SQL query, we will create a
variable ($current_date) that will store the
current date as of this point of execution.
*/
$current_date = time();

log_msg("Script Start Time: $current_date", true);

/*
Now we will build our SQL query. We will select
every field, from every row that has a date field
value of more then the current date ($current_date).
Finally, we will order our results in ascending order
by our date column.
*/
$sql = <<<SQL
SELECT * FROM my_tbl
WHERE date > '$current_date'
ORDER BY date ASC
SQL;

log_msg("nBuilding SQL Query...", true);

/*
Now we will execute our SQL query
*/
$result = @mysql_query($sql);

log_msg("nExecuting SQL Query...", true);

/*
And unset our lieteral SQL query ($sql) variables in
order to free up that little bit of memory.
*/
unset($sql);

/*
Now we will check how many rows of data there are. If
less than one we will immedatly exit, otherwise we will
output the number of emails to be sent and continue
script execution.
*/
$num_rows = @mysql_num_rows($result);

if($num_rows < 1)
{
log_msg("nNo emails matching SQL Query criteria found. Script halted.", true);
exit;
}

/*
Now we will loop through all the rows of data which
were applicable as per our SQL query and fetch them as
objects via a variable ($row).
*/
while($row = @mysql_fetch_object($result))
{
log_msg("n<strong>$num_rows</strong> Emails to be sent", true);

/*
The first piece of information we need to know is
how long until the next email needs to be sent so
we can tell the script to go to sleep until then.
To attain this information we will take away the
date that the email needs to be sent at from the
current date.
*/
$time_until_next_email_is_sent = (time() - $row->date);

log_msg("Next email to be sent in $time_until_next_email_is_sent seconds...", true);
log_msg("Sleeping...", true);

/*
Like previously mentioned, we will tell the script
to go to sleep until the next email needs to be
sent. This is done by calling the sleep function
and passing it a time in seconds until the next
email is to be sent
($time_until_next_email_is_sent).
*/
sleep($time_until_next_email_is_sent);

/*
If we are at this point of the loop it must be time
to send the next email. We will do this by calling
the mail() function and passing it several pieces of
information (to, subject, message, headers) all of
which are stored in our database.
*/
if(!@mail($row->to, $row->subject, $row->message, $row->headers))
log_msg("Successfully sent email to " . $row->to, true);
}
else
{
log_msg("Failed to send email to " . $row->to, true);
}

/*
Now if that was not the last applicable record in our
result we will start the loop over again with a new row
of data and decrement our row count. Otherwise, we will
now break out of the loop and continue execution of the
remainder of the script.
*/
$num_rows--;
}

/*
If we have made it to this section of the script it means
we have successfully sent all the applicable emails in the
database. Therefore we will halt the scipt .
*/
log_msg("All emails sent. Script Finished. Script execution took " . (time() - $current_date) . " seconds.", true);
exit;

?></pre>[/code]
×

Success!

Help @kproc spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...