PHPMailer and Autoload

! ) Fatal error: Uncaught Error: Class 'PHPMailer' not found in G:\......\PHP\sendemail\public\index.php on line *15*
( ! ) Error: Class 'PHPMailer' not found in G:\......\PHP\sendemail\public\index.php on line *15*

I am getting this error on my local machine.

This is the structural causality of the code →

.
Isn’t autoload capable of autoloading PHPmailer class?

Full Code on public/index.php→

<?php 
echo "Yes Connected!";


/**
 * PHPMailer Autoloader
 */
require '../vendor/autoload.php';


/**
 * Configure PHPMailer with your SMTP Server settings
 */

$mail = new PHPMailer();
$mail->isSMTP(); 
$mail->Host = 'mail.example.com';
$mail->Port = 587;
$mail->SMTPAuth = true; 
$mail->Username = 'email@gmail.com'; 
$mail->Password = "password";
$mail->SMTPSecure = 'tls';

/**
 * Set an email
 */
$mail->setForm('from@we.com');
$mail->addAddress('recipent@we.com');
$mail->Body = 'This is a test message';

if ($mail->send()) {
  echo "Yups You have send a mail Grid";
}else {
  echo "Oops! Something went wrong";
}

PHPMailer is here →

The class PHPMailer is actually in the namespace PHPMailer\PHPMailer. If you omit that, then no, the autoloader can’t find it.

The correct syntax would be

<?php

require __DIR__ . '/vendor/autoload.php';

$mailer = new \PHPMailer\PHPMailer\PHPMailer();

However, since that’s rather longwinded, you can also use the use statement to indicate to PHP that each time you instance of a PHPMailer class, you actually mean PHPMailer\PHPMailer\PHPMailer.

<?php

use PHPMailer\PHPMailer\PHPMailer;

require __DIR__ . '/vendor/autoload.php';

$mailer = new PHPMailer();
// etc

You may want to read up on the usage of namespaces in PHP: https://www.php.net/manual/en/language.namespaces.php

2 Likes

The following link might also help even though it uses composer which I use as my auto loader is also very helpful. I know I was having a heck of a time with autoloaders, but a light bulb when on in my head after reading this page. https://phpenthusiast.com/blog/how-to-autoload-with-composer

1 Like

Hi there,

Finally, this combination worked, and emails are getting sent →

use PHPMailer\PHPMailer\PHPMailer;
require '../vendor/autoload.php';