Phpmailer: Please help what i did wrong. I got Fatal error: Class 'PHPMailer\PHPMailer\PHPMailer' not found

Created on 11 Sep 2020  Â·  10Comments  Â·  Source: PHPMailer/PHPMailer

<?php
/*So before I installed PHPmailer via composer and I checked the directory path and typo are all right 
but still not working. Now I do it manually. I downloaded the package from 
https://github.com/PHPMailer/PHPMailer and extract the zip file. Then I upload to server 
the Language folder and src folder (which include: Exception.php, OAuth.php, PHPMailer.php, POP3.php, SMTP.php) 
and I store all into the same directory called PHPmailer. But this still not working*/

/* I also tried to remove these use 2 lines then write as 
$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP(); */
use PHPMailer\PHPMailer\PHPMailer; //---^^^---
use PHPMailer\PHPMailer\Exception; // ---^^^---

require_once('../include/PHPmailer/src/PHPMailer.php');
require_once('../include/PHPmailer/src/SMTP.php');
require_once('../include/PHPmailer/src/Exception.php’);

    class Forgotpassword {
        public function __construct(){
            $this->run();
        }

        public function run(){
            $this->print_forgotpassword();
        }

        public function print_forgotpassword(){
            global $pdo;
            if(isset($_POST['submit_newpasswordRequest']) && $_POST['email']) {
                $email = $_POST["email"];
                $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); //Clean variables if form is submitted
                $sql = "SELECT EXISTS (SELECT * FROM users WHERE email_address = ?) AS CNT";
                $stmt = $pdo->prepare($sql);
                $stmt->execute([$email]);
                $email_exist = $stmt->fetchColumn();

                //if that email not exist
                if (!$email_exist){
                    echo '<div class="error">The email adresss you entered does not match our records. Please try again.</div>';
                    echo '<br />';
                    echo '<a href="javascript:history.go(-1)">Go Back</a>';

                //if that email exist then insert Temp Table to creadte random md5 keyhash  
                } else {
                    $expFormat = mktime(date("H"), date("i"), date("s"), date("m") ,date("d")+1, date("Y"));
                    $expDate = date("Y-m-d H:i:s",$expFormat);
                    $string = $email;
                    $keyhash = md5(2418*2+$string);
                    $addKey = substr(md5(uniqid(rand(),1)),3,10);
                    $keyhash = $keyhash . $addKey;
                    $sql = "INSERT INTO password_reset_temp (email, keyhash, expDate) values (?, ?, ?)";
                    $stmt = $pdo->prepare($sql);
                    $stmt->execute([$email, $keyhash, $expDate]);

                   //then send reset link to user email using md5hash via PHPmailer
                   $body = $output; 
                    $output='<p>Dear user,</p>';
                    $output.='<p>Please click the following link to reset your password.</p>';
                    $output.='<p>-------------------------------------------------------------</p>';
                    $output.='<p><a href="https://www.website.com/?resetpassword.php
                    ?key='.$keyhash.'&email='.$email.'&action=/?forgotpassword target="_blank">
                    https://www.website.com/?resetpassword.php
                    ?key='.$keyhash.'&email='.$email.'&action=/?forgotpassword</a></p>'; 
                    $output.='<p>-------------------------------------------------------------</p>';
                    $output.='<p>Please be sure to copy the entire link into your browser.
                    The link will expire after 1 day for security reason.</p>';
                    $output.='<p>If you did not request this forgotten password email, no action 
                    is needed, your password will not be reset. However, you may want to log into 
                    your account and change your security password as someone may have guessed it.</p>';   
                    $output.='<p>Thanks,</p>';
                    $output.='<p>website Team</p>';

                    //PHPmailer 
                    $mail = new PHPMailer; //Instantiation & passing true enables exceptions

                    //Server settings
                    /*$mail->SMTPDebug = SMTP::DEBUG_SERVER; 
                    $mail->IsSMTP(); 
                    $mail->Host = "mail.website.com"; 
                    $mail->SMTPAuth = true;  
                    $mail->Username = "[email protected]"; 
                    $mail->Password = "12345"; 
                    $mail->SMTPSecure = "ssl";  
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; 
                    $mail->Port = "465"; 

                    //Sender & Recipient
                    $mail->From('[email protected]', 'Website');
                    $mail->AddAddress('$email');
                    $mail->addReplyTo('[email protected]', 'No reply');

                    // Content
                    $mail->IsHTML(true); // Set email as HTML format
                    $mail->Subject = 'Password Recovery - website.com';
                    $mail->Body    = '$body';
                    $mail->AltBody = '$body'; //nonHTML mail recipient
                    if(!$mail->Send()){
                    echo "Mailer Error: " . $mail->ErrorInfo;
                    } else {
                    echo "<div class='error'>
                    <p>An email has been sent to you with instructions on how to reset your password.</p>
                    </div><br /><br /><br />";
                    }
                }
            }       

        //forgot password form
                echo '<div id="forgot_wrapper">';
            echo '<div id="forgot_container">';
                echo '<form method="post" action="/?forgotpassword">';
                echo '<p>Enter the email address associated with your account.</p>';
                echo '<input type="text" name="email">';
                echo '<input type="submit" name="submit_newpasswordRequest">';
                echo '</form>';
            echo '</div>'; //ends forgot_container
            echo '</div>'; //ends forget_wrapper

        }       


    }
?>

Most helpful comment

Next to that, $key = md5(2418*2+$email); is gonna be iffy as well, since you are using math operator to add a string to a number. Also, the key you are generating is quit an exotic way to do this, it is not safer than just hashing a random input.
From security perspective, you send: $link="<a href='www.mywebiste.com/reset.php?key=".$email."&reset=".$pass."'
This should never be done! You just created a random key, make use of that! Now you are sending the actual password of someone! MD5 is not secure, there are ways of retrieving the password by having the MD5 hash...

All 10 comments

This is not a PHPMailer problem, you have a syntax error at

$error .= array_push(['error' => 'The email address you entered is incorrect or the account is not existed.']);

Because you are not passing a variable to the function.

Next to that, $key = md5(2418*2+$email); is gonna be iffy as well, since you are using math operator to add a string to a number. Also, the key you are generating is quit an exotic way to do this, it is not safer than just hashing a random input.
From security perspective, you send: $link="<a href='www.mywebiste.com/reset.php?key=".$email."&reset=".$pass."'
This should never be done! You just created a random key, make use of that! Now you are sending the actual password of someone! MD5 is not secure, there are ways of retrieving the password by having the MD5 hash...

What the others said! Rather than reinventing the wheel here, if you want to implement password resets securely, do what this article says.

I really appreciate it. It helps a lot. @NiklasBr your right. there were some syntax error, prepare statement and also the include phpmailer files which I remove as below
PHPMailer\PHPMailer\Exception;
require 'PHPMailer/src/Exception.php';
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';

@XL-2000 I'm working on MD5 hash now. Very good point!b and also @Synchro interesting read

@NiklasBr @Synchro @XL-2000 Hey guys, I fix all syntax errors and prepare statements and update the code. But now I got 'PHPMailer\PHPMailer\PHPMailer' not found #2135

I've tried different ways include PHPMailer file but still got errors. Your input is appreciated.

First include the required files using require_once(...);
Then code use PHPMailer\PHPMailer\PHPMailer;
make sure your paths match and do not mix forward and backward slashes

First include the required files using require_once(...);
Then code use PHPMailer\PHPMailer\PHPMailer;
make sure your paths match and do not mix forward and backward slashes

So I installed PHPmailer via composer and I did follow your instruction. I checked the directory path and typo are all right but still not working. Now I do it manually as below:

  1. Downloaded the package from https://github.com/PHPMailer/PHPMailer and extract the zip file
  2. Then I upload to server the Language folder and src folder (which include: Exception.php, OAuth.php, PHPMailer.php, POP3.php, SMTP.php) and I store all into the same directory called PHPmailer

1st method not working:
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once('../include/PHPmailer/src/PHPMailer.php');
require_once('../include/PHPmailer/src/SMTP.php');
require_once('../include/PHPmailer/src/Exception.php’);

2nd method still not working
require_once('../include/PHPmailer/src/PHPMailer.php');
require_once('../include/PHPmailer/src/SMTP.php');
require_once('../include/PHPmailer/src/Exception.php’);

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP();

still got error (Fatal error: Class 'PHPMailer' not found ) What could go wrong? Please advice.

Sigh, look what you wrote there yourself.

 First include the required files using `require_once(...);`
 Then code `use PHPMailer\PHPMailer\PHPMailer;`
 make sure your paths match and do not mix forward and backward slashes

So I installed PHPmailer via composer and I did follow your instruction. I checked the directory path and typo are all right but still not working. Now I do it manually as below:

  1. Downloaded the package from https://github.com/PHPMailer/PHPMailer and extract the zip file
  2. Then I upload to server the Language folder and src folder (which include: Exception.php, OAuth.php, PHPMailer.php, POP3.php, SMTP.php) and I store all into the same directory called PHPmailer
> 1st method not working:
> use PHPMailer\PHPMailer\PHPMailer;
> use PHPMailer\PHPMailer\Exception;
> 
> require_once('../include/PHPmailer/src/PHPMailer.php');
> require_once('../include/PHPmailer/src/SMTP.php');
> require_once('../include/PHPmailer/src/Exception.php’);

2nd method still not working
require_once('../include/PHPmailer/src/PHPMailer.php');
require_once('../include/PHPmailer/src/SMTP.php');
require_once('../include/PHPmailer/src/Exception.php’);

$mail = new PHPMailer\PHPMailer\PHPMailer();
$mail->IsSMTP();

still got error (Fatal error: Class 'PHPMailer' not found ) What could go wrong? Please advice.

And what you actually do in your code.

Yanked this form an old (but working) sandbox running PHPMailer 6.1.5

require_once($_SERVER['DOCUMENT_ROOT'].'/includes/PHPMailer/src/PHPMailer.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/PHPMailer/src/SMTP.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/PHPMailer/src/Exception.php');
use PHPMailer\PHPMailer\PHPMailer;

$GLOBALS['mailer'] = new PHPMailer;

Also note the missing "()" at the end of the "new" call, where you create the instance

The "missing ()" doesn't make any difference, though it's against PSR-12 coding standards, so I tend to always make sure they're there now.

This whole thread is a great example of why it's a bad idea to manage your own dependencies: learn to use composer. Doing it yourself adds so much unnecessary complexity and opportunities for confusion. Any time you use require_once, it's an admission that you're not entirely sure how your app loads dependencies, and that's a recipe for bugs.

Was this page helpful?
0 / 5 - 0 ratings