PHPMailer in CodeIgniter

In a previous post I talked about how to use the library PHPMailer to send emails from our website without having our own mail server running on the machine. This time we will go a step further and explain how to integrate this library in our CodeIgniter project and not die in the attempt.

The first thing we do, if we have not done it yet, will be to download the library. Once we unzip the library, we can rename the folder named PHPMailer and move it to the folder /system/application/libraries (for CodeIgniter 1.7.3 or previous) or to the folder /application/libraries/ (for CodeIgniter 2.0 or later) in our CodeIgniter application. Once we did it so, we can start to implement our own library, which will be in charge of including PHPMailer into our application. To do this we have to create a new PHP file in the CodeIgniter’s library directory called my_phpmailer.php. In this file we will write the following code:

if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class My_PHPMailer {
    public function My_PHPMailer() {

Now we can use the library PHPMailer from our controllers. For this we have to write the following code in the controller:

class My_Controller extends Controller {
    public function My_Controller(){
    public function send_mail() {
        $mail = new PHPMailer();
        $mail->IsSMTP(); // we are going to use SMTP
        $mail->SMTPAuth   = true; // enabled SMTP authentication
        $mail->SMTPSecure = "ssl";  // prefix for secure protocol to connect to the server
        $mail->Host       = "";      // setting GMail as our SMTP server
        $mail->Port       = 465;                   // SMTP port to connect to GMail
        $mail->Username   = "";  // user email address
        $mail->Password   = "password";            // password in GMail
        $mail->SetFrom('', 'Firstname Lastname');  //Who is sending the email
        $mail->AddReplyTo("","Firstname Lastname");  //email address that receives the response
        $mail->Subject    = "Email subject";
        $mail->Body      = "HTML message
"; $mail->AltBody = "Plain text message"; $destino = ""; // Who is addressed the email to $mail->AddAddress($destino, "John Doe"); $mail->AddAttachment("images/phpmailer.gif"); // some attached files $mail->AddAttachment("images/phpmailer_mini.gif"); // as many as you want if(!$mail->Send()) { $data["message"] = "Error: " . $mail->ErrorInfo; } else { $data["message"] = "Message sent correctly!"; } $this->load->view('sent_mail',$data); } }

With this code we have already implemented our controller for sending emails from our application in CodeIgniter using the library PHPMailer.

26 thoughts on “PHPMailer in CodeIgniter

Leave a Reply

Your email address will not be published. Required fields are marked *