How to Send Email using CodeIgniter

Email is very important in web applications. When a user signs up, we might want to send them an email to verify their email address and allow the user to confirm subscription. We also use email to reset forgotten passwords, send invoice and receipts to customers, etc. CodeIgniter makes it super easy for us to send emails from our application using a variety of options.

CodeIgniter has a built-in email library that we can work with when sending emails.

In this tutorial, you will learn

CodeIgniter Email Configuration

We need to have a central place where we can manage the email settings. CodeIgniter does not come with a config file for emails so we will have to create one ourselves.

Create a file email.php in the directory application/config

Add the following code to email.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

$config = array(
    'protocol' => 'smtp', // 'mail', 'sendmail', or 'smtp'
    'smtp_host' => 'smtp.example.com', 
    'smtp_port' => 465,
    'smtp_user' => This email address is being protected from spambots. You need JavaScript enabled to view it.',
    'smtp_pass' => '12345!',
    'smtp_crypto' => 'ssl', //can be 'ssl' or 'tls' for example
    'mailtype' => 'text', //plaintext 'text' mails or 'html'
    'smtp_timeout' => '4', //in seconds
    'charset' => 'iso-8859-1',
    'wordwrap' => TRUE
);

HERE,

Note: for sending emails to work, you should provide valid configuration parameters. Dummy parameters will not be able to send emails.

CodeIgniter Email View

In this section, we will create the view that will send the email to the recipient.

Create a new directory email in application/views

Create a new file contact.php application/views/email

Add the following code to application/views/email/contact.php

<!DOCTYPE html>
<html>
    <head>
        <title>CodeIgniter Send Email</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div>
            <h3>Use the form below to send email</h3>
            <form method="post" action="<?=base_url('email')?>" enctype="multipart/form-data">
                <input type="email" id="to" name="to" placeholder="Receiver Email">
                <br><br>
                <input type="text" id="subject" name="subject" placeholder="Subject">
                <br><br>
                <textarea rows="6" id="message" name="message" placeholder="Type your message here"></textarea>
                <br><br>
                <input type="submit" value="Send Email" />
            </form>
        </div>
    </body>
</html>

HERE,

CodeIgniter Email Controller

Let's now create the controller that will be handling sending email

Create a new file EmailController.php in application/controllers/EmailController.php

Add the following code to EmailController.php

<?php

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

class EmailController extends CI_Controller {

    public function __construct() {
        parent:: __construct();

        $this->load->helper('url');
    }

    public function index() {
        $this->load->view('email/contact');
    }

    function send() {
        $this->load->config('email');
        $this->load->library('email');
        
        $from = $this->config->item('smtp_user');
        $to = $this->input->post('to');
        $subject = $this->input->post('subject');
        $message = $this->input->post('message');

        $this->email->set_newline("\r\n");
        $this->email->from($from);
        $this->email->to($to);
        $this->email->subject($subject);
        $this->email->message($message);

        if ($this->email->send()) {
            echo 'Your Email has successfully been sent.';
        } else {
            show_error($this->email->print_debugger());
        }
    }
}

HERE,

Let's now define the email routes

Email Routes

Add the following routes to application/config/routes.php

$route['send-email'] = 'email controller';
$route['email'] = 'email controller/send';

We can now load the contacts form in the web browser

Let's start the built-in PHP server

Open the terminal/command line and browse to the root of your application. In my case, the root is located in drive C:\Sites\ci-app

cd C:\Sites\ci-app

start the server using the following command

php -S localhost:3000

Load the following URL in your web browser

http://localhost:3000/send-email

You should be able to see the following form

Enter the recipient email, subject, and email message then click on Send Email. If your email configurations are set properly, then you should be able to see the successful message.

Summary

The built-in email library makes it easy for us to send emails with minimal code. The library is also very flexible in the sense that you can configure it to meet your requirements.

 

YOU MIGHT LIKE: