To send emails via Gmail in CodeIgniter 3 using PHPMailer, you’ll first need to include PHPMailer in your project. Here’s a step-by-step guide to setting it up:
Step 1: Download PHPMailer
- Download the latest version of PHPMailer.
- Extract the downloaded files and place the
src
folder into your CodeIgniter project’sapplication/third_party/
directory.
Step 2: Load PHPMailer in CodeIgniter
Create a new file in application/libraries
called Phpmailer_lib.php
and add the following code to load the PHPMailer library:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class Phpmailer_lib {
public function __construct() {
require_once(APPPATH . 'third_party/src/Exception.php');
require_once(APPPATH . 'third_party/src/PHPMailer.php');
require_once(APPPATH . 'third_party/src/SMTP.php');
}
public function load() {
$mail = new PHPMailer();
return $mail;
}
}
Step 3: Configure the Email Function in Your Controller
Create a method in your controller to send the email. Here’s an example:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
class EmailController extends CI_Controller {
public function __construct() {
parent::__construct();
// Load PHPMailer
$this->load->library('Phpmailer_lib');
}
public function send_email() {
// Load PHPMailer
$mail = $this->phpmailer_lib->load();
try {
// SMTP configuration
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_email@gmail.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
// Email settings
$mail->setFrom('your_email@gmail.com', 'Your Name');
$mail->addReplyTo('your_email@gmail.com', 'Your Name');
$mail->addAddress('recipient_email@gmail.com'); // Recipient's email
$mail->Subject = 'Test Email';
$mail->isHTML(true);
$mail->Body = '<p>This is a test email sent using PHPMailer in CodeIgniter 3</p>';
// Send email
if ($mail->send()) {
echo 'Email has been sent successfully.';
} else {
echo 'Email could not be sent. Error: ' . $mail->ErrorInfo;
}
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ' . $e->getMessage();
}
}
}
Step 4: Access the Function in Your Browser
Go to http://yourdomain.com/index.php/emailcontroller/send_email
to trigger the email send function.
Leave a Reply