I'm trying to send automatic emails every week with a cronjob. However, I get the error message "Mailer Error: Message body empty".
For the email, I use a .html template.
When I trigger the .php script by calling its URL it works perfectly. But when it's triggered by the cronjob it gives me that message.
The host I use is hostinger and I'm using their internal cronjob system.
This is my .php script.
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';
$msg = file_get_contents('./contact.html');
$msg = str_replace('$message', $message, $msg);
$mail = new PHPMailer;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = 'myusername';
$mail->Password = 'mypassword';
$mail->setFrom('frommail@mail.com', 'frommail');
$mail->addReplyTo('mail@mail.com', 'mail');
$mail->addAddress($username I get from the database, $username I get from the database);
$mail->Subject = 'subject';
$mail->MsgHTML($msg);
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
$response = ["Result" => "error"];
echo json_encode($response);
} else {
$response = ["Result" => "success"];
echo json_encode($response);
}
It's very likely that your cron job is run by a different user than when run via your web server, and that user may not have ownership or sufficient permissions to read the contact.html
file. If msgHTML()
fails, it will return an empty string, so you could check that before you try to send (though I notice you have omitted the send()
call from the script in your question, and you don't show any error handling either).