Reputation: 415
I have a cron task that looks like:
00 12 * * 1 /usr/bin/php /path/to/php/script/cron_job.php
45 20 * * 1 /usr/bin/php /path/to/php/script/cron_job.php
00 12 * * 2 /usr/bin/php /path/to/php/script/cron_job.php
45 20 * * 2 /usr/bin/php /path/to/php/script/cron_job.php
00 12 * * 3 /usr/bin/php /path/to/php/script/cron_job.php
45 20 * * 3 /usr/bin/php /path/to/php/script/cron_job.php
00 12 * * 4 /usr/bin/php /path/to/php/script/cron_job.php
45 20 * * 4 /usr/bin/php /path/to/php/script/cron_job.php
00 12 * * 5 /usr/bin/php /path/to/php/script/cron_job.php
45 20 * * 5 /usr/bin/php /path/to/php/script/cron_job.php
00 12 * * 6 /usr/bin/php /path/to/php/script/cron_job.php
45 20 * * 6 /usr/bin/php /path/to/php/script/cron_job.php
The php code in that file looks like this:
$employeesArray = array(
'[email protected]',
'[email protected]',
'[email protected]'
);
if (date('A', time()) == 'AM')
{
foreach($employeesArray as $employee)
{
echo $employee.' - AM';
$mail->
addTo($employee)->
setFrom('[email protected]')->
setHtml('Dont forget to Log In.');
$result = $sendgrid->smtp->send($mail);
echo ' -> '.$result.'<br />';
}
}
else
{
foreach($employeesArray as $employee)
{
echo $employee.' - PM';
$mail->
addTo($employee)->
setFrom('[email protected]')->
setHtml('Dont forget to Log Out.');
$result = $sendgrid->smtp->send($mail);
echo ' -> '.$result.'<br />';
}
}
This script is used to send all employees a message first thing in the morning before they start and just before their shift ends; only on Monday to Friday. The emails are going out, but Employee1 and Employee2 are receiving 4 copies of the message and Employee3 is receiving 7 copies. When I run the script manually by navigating to the page "cron_job.pnp" in a web browser it only sends once to each so I'm assuming it is a problem with my cron job firing more than once.
Thanks in advance for your help.
Upvotes: 1
Views: 1424
Reputation: 360872
You're doing an ->addTo
call on every iteration of the loop. You're basically building up an array of addresses on every iteration..
iteration #1:
"To:" list is: (empty)
add: user#1
send() (one email goes out)
iteration #2:
"To:" list is: user #1
add: user #2
send() (two emails go out)
iteration #3
"To:" list is: user #1, user #2
add: user #3
send() (three emails go out)
etc...
Since you've tagged this with PHPMailer, you need to $mailer->ClearAddresses()
on every loop, so that the stored To:
names get erased:
foreach($user as $user) {
$mail->AddUser($user);
$mail->send();
$mail->ClearAddresses();
}
Upvotes: 2