Reputation:
I am new for PHPMailer and when I have set the code to send an email with PHPMailer it shows me an error with:
Mailer Error: Message body empty
I have tried many links from stack also like this and this, but couldn't got the solution.
Below is my code
<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
//Create a new PHPMailer instance
$mail = new PHPMailer;
$mail->isSMTP();
$mail->SMTPDebug = 2;
$mail->Host = '[email protected]';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = '*****';
$mail->setFrom('[email protected]', 'test');
$mail->addReplyTo('[email protected]', 'Test');
$mail->addAddress('[email protected]', 'Receiver Name');
$mail->Subject = 'PHPMailer SMTP message';
$mail->msgHTML(file_get_contents('message.html'), __DIR__);
$mail->AltBody = 'This is a plain text message body';
/*$mail->addAttachment('test.txt');*/
if (!$mail->send()) {
echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
echo 'Message sent!';
}
?>
How can I resolve this?
Upvotes: 0
Views: 1507
Reputation: 37710
The call to msgHTML()
will set both plain and HTML body parts. If your call to file_get_contents
returns nothing, you will end up with an empty body, which will trigger the error you are seeing.
So check that call first:
$body = file_get_contents('message.html');
var_dump($body);
$mail->msgHTML($body, __DIR__);
This will still show the error, but you will be able to check your content first. If your file called message.html
is not empty, check using an absolute path (e.g. by using __DIR__ . '/message.html'
), and if that still fails to produce a result, check that the user accessing the file has sufficient permissions to do so.
Note that msgHTML
also sets AltBody
, so unless you specifically want to override that, you don’t need to set that as well.
Upvotes: 1