Reputation: 3594
I have a site that uses a framwork called(documentation here). A WordPress framework based on laravel, but I don't quite understand how the emails work.
The direct question is: how can I use PHPMailer to send emails?
At the moment, and for testing purposes, I want an email to be sent as soon as a page loads, so my controller method looks like the following:
<?php
namespace Theme\Controllers;
use Themosis\Route\BaseController;
use Phpmailer\PHPMailer;
class OtherController extends BaseController {
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = "My username";
$mail->Password = "mypassword";
$mail->setFrom('[email protected]', 'The name');
$mail->addReplyTo('[email protected]', 'The name');
$mail->addAddress('[email protected]', 'Address');
$mail->Subject = 'Contact us form sent';
$mail->Body = 'This is a plain-text message body';
return "Email sent";
}
I installed PHPMailer using composer, as per their documentation here.
When I hit the url, I get the following error:
Fatal error: Uncaught Symfony\Component\Debug\Exception\FatalThrowableError: Class
'Phpmailer\PHPMailer' not found in
/var/www/html/htdocs/content/themes/amarula/resources/controllers/OtherController.php on line
141
Though the error message, I assume that the problem is in how I am attempting to access the mailer class, which is sitting in the vendor folder.
From the root of my application until my controller, the structure looks like the one below:
Ultimately, the PHPMailer class sits under the vendor folder, like in the structure below:
How do I access that class and send the email through my controller?
Upvotes: 0
Views: 308
Reputation: 37760
You have this import:
use Phpmailer\PHPMailer;
That's not correct; it should be:
use PHPMailer\PHPMailer\PHPMailer;
The reason for this "triple name" is that it represents the PHPMailer class in the PHPMailer package belonging to the PHPMailer organisation.
One other thing that's kind of important - you won't receive any messages because you're never calling $mail->send()
.
Upvotes: 1
Reputation: 19
Firstly - PHPmailer\PHPMailer instead of Phpmailer\PHPMailer (https://github.com/PHPMailer/PHPMailer/blob/master/src/PHPMailer.php)
Second, you trying to find PHPMailer reletavely in namespace of your code.
controllers/OtherController/PHPMailer/PHPMailer.php
And, of course, it doesn't exsits.
You should use \PHPMailer\PHPMailer
to find class by absolute path
For more information, read about namespaces - https://www.php.net/manual/en/language.namespaces.rationale.php
Upvotes: 1