I got a cronjob that executes a PHP script every 5 minutes in order to send a welcome letter to new members.
My goal is to fetch the data from MySQL, pull it into an array, loop through the results and mail each result to a recipient using PHPs mail()
function.
The mail()
part is not working for some reason and I am 100% sure that mail()
is configured and working because I can use mail()
outside the foreach loop.
Example code below:
Fetch data from MySQL and store it in an array:
while ($row = $result->fetch_assoc()) {
$tickets[] = array($row['id'], $row['namn'], $row['epost'],
$row['meddelande'], $row['datum']);
}
$tickets
is an array.
Loop through the results and mail it:
foreach ($tickets as $ticket) {
if (mail("mymail@example.org", "Msg from $ticket[1]", "$ticket[3]", "From: $ticket[2]")) { // Always called, but doesn't send the mail
$query = 'UPDATE ticket SET skickat = 1 WHERE id = ?';
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('s',$ticket[0]);
$stmt->execute();
} else {
sleep(5);
$query = 'UPDATE ticket SET skickat = 1 WHERE id = ?';
$stmt = $db->prepare($query);
$stmt->bind_param('s',$ticket[0]);
$stmt->execute();
}
} else {
die('The email could not be sent');
}
}
The code works, and it updates the MySQL record to skickat = 1 so I know that the code got executed how ever, it doesn't send the mail.
I don't have access to the error.log that Apache creates and I get no errors with PHP errors turned on.
What am I missing?
I'm using Apache 2 with PHP 7
@AlexHowansky Yeah I know and you're right. I did test `mail()` outside the foreach loop, with the same params and then it worked, on both ends. The reason why I want to use mail() for now is because i'm just testing it out. – Jonas Johansson Nov 02 '17 at 20:15