I am trying to implement phpmailer in my codeigniter 3 project so I required it in my composer.json and it created a phpmailer folder in the application/vendor folder. I then set my composer autoload in config.php as follows:
$config['composer_autoload'] = 'vendor/autoload.php';
After that I created a Phpmailer_library.php file inside the libraries folder:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Phpmailer_library
{
public function __construct()
{
log_message('Debug', 'PHPMailer class is loaded.');
}
public function load()
{
require_once(APPPATH.'vendor/phpmailer/phpmailer/src/PHPMailer.php');
require_once(APPPATH.'vendor/phpmailer/phpmailer/src/SMTP.php');
$objMail = new PHPMailer\PHPMailer\PHPMailer();
return $objMail;
}
}
Inside my SendEmail.php model I loaded the phplibrary in the constructor:
public function __construct(){
$this->load->library('Phpmailer_library');
}
But when it tries to send an email an error occurs:
So I tried to trace line 107 inside of my SendEmail.php model and this is the code snippet:
$mail = $this->Phpmailer_library->load();
I don't know why Call to a member function load() on null is occurring. Is there a mistake that i missed in my code? this error has been bugging my day.
I also try to follow the approved answer here but still did not work.
How to integrate PHPMailer with Codeigniter 3
My Answer:
defined('BASEPATH') OR exit('No direct script access allowed');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require FCPATH.'vendor/autoload.php';
class Phpmailer_library {
public function __construct() {
$this->mail = new PHPMailer(true);
}
public function send_email($to, $subject, $message) {
try {
$this->mail->setFrom('your_email@example.com', 'Your Name');
$this->mail->addAddress($to);
$this->mail->Subject = $subject;
$this->mail->Body = $message;
$this->mail->isSMTP();
$this->mail->Host = 'smtp.example.com';
$this->mail->SMTPAuth = true;
$this->mail->Username = 'your_smtp_username';
$this->mail->Password = 'your_smtp_password';
$this->mail->SMTPSecure = 'tls';
$this->mail->Port = 587;
$this->mail->send();
return true;
} catch (Exception $e) {
return false;
}
}
}
?>
Now you can load the Phpmailer_library in your controller and use the send_email method to send emails. Make sure to replace the placeholders with your actual email and SMTP details.
Rate this post
4 of 5 based on 2236 votesComments