This is my simple function to send static HTML mail which is inside myFramework.php file:
include_once('PHPMailer.php');
function sendMail($toAddress) {
//Usual setup
$mail = new PHPMailer(); // Error is showing for this line
$mail->setFrom('email@example.com');
$mail->addAddress($toAddress);
$mail->Subject = 'PHPMailer mail() test';
$mail->msgHTML("<h1>This is an HTML message</h1>");
if (!$mail->send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
}
But when I try to send Email it does not send the email and produces an error which is as follows:
Fatal error: Class ‘PHPMailer’ not found …
Why it is not creating an object even if I have imported the PHPMailer file correctly? Or is it wrong?
All the sample code I just looked at uses this rather than what you have:
$mail = new PHPMailer; // without the brackets
Does that make any difference? I keep meaning to try PHPMailer but never get around to it.
It also seems to include “PHPMailerAutoload.php” rather than the file you include. Again, I’ve no idea if it makes any difference. Sample code I was looking at here: https://github.com/PHPMailer/PHPMailer/wiki/Tutorial
After going through PHPMailer upgrade guide on Github I changed my code as follows:
// Wrapped PHPMailer.php into phpMailer folder
require_once 'phpMailer/PHPMailer.php';
// Using PHPMailer Namespace as specified PHPMailer developers
use PHPMailer\PHPMailer\PHPMailer;
Then create PHPMailer object and works absolutely fine!
That’s because include_once and require_once, among others, are not functions, they are “language constructs” and do not need brackets [sic parentheses] even though code that has them written in function syntax is ubiquitous.
… look like functions, some look like constants, and so on - but they’re not, really: they are language constructs …
I think that was in response to me saying to try having no brackets on the end of the new PHPMailer line, rather than on the include / require lines. That’s certainly what I was driving at.
Might want to do yourself a favor and use composer to setup your project. It will simplify things and help in the long run.
mkdir mailer
cd mailer
composer require phpmailer/phpmailer
# file mailer.php
<?php
require 'vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
$mailer = new PHPmailer();
The vendor/autoload.php file is generated by composer and takes care of locating your various third party classes. Nowadays, any third party library worth using supports composer.