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
  • CodeIgniter Email View
  • CodeIgniter Email Controller
  • Email Routes

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' => 'no-reply@example.com',
    '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,

  • ‘protocol’ => ‘smtp’, specifies the protocol that you want to use when sending email. This could be Gmail smtp settings or smtp settings from your host
  • ‘smtp_host’ => ‘smtp.example.com’,specifies the smtp host. For example, if you want to use Gmail then you would have something like smtp.gmail.com
  • ‘smtp_port’ => 465, an open port on the specified smtp host that has been configured for smtp mail
  • ‘smtp_user’ => ‘no-reply@example.com’, the email address that will be used as the sender when sending emails. This should be a valid email address that exists on the server
  • ‘smtp_pass’ => ‘12345!’, the password to the specified smtp user email
  • ‘smtp_crypto’ => ‘ssl’, specifies the encryption method to be used i.e. ssl, tls etc.
  • ’email type’ => ‘text’, sets the mail type to be used. This can be either plain text or HTML depending on your needs.
  • ‘smtp_timeout’ => ‘4’, specifies the time in seconds that should elapse when trying to connect to the host before a timeout exception is thrown.
  • ‘charset’ => ‘iso-8859-1’, defines the character set to be used when sending emails.
  • ‘wordwrap’ => TRUE is set to TRUE then word-wrap is enabled. If it is set to FALSE, then word-wrap is not enabled

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,

  • We have a basic HTML form that accepts the email, subject and message then passes the parameters to email route.

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,

  • class EmailController extends CI_Controller {…} defines our email controller that expands the parent CodeIgniter controller.
  • public function __construct() {…} defines the child constructor that calls the parent constructor method.
  • public function index() {…} defines the index method that displays the contact form
  • function send() {…} defines the method that sends the email
    • $this->load->config(’email’); loads the email configuration settings
    • $this->load->library(’email’); loads the email library
    • $from = $this->config->item(‘smtp_user’); gets the sender id from the email configuration file that we defined.
    • $to = $this->input->post(‘to’); gets the to value from the submitted form
    • $subject = $this->input->post(‘subject’); sets the email subjected from the form
    • $message = $this->input->post(‘message’); sets the email message from the form
    • $this->email->set_newline(“\r\n”); defines the new line characters for emails
    • $this->email->from($from); sets the sender email address
    • $this->email->to($to); sets the recipient email address
    • $this->email->subject($subject); sets the email subject
    • $this->email->message($message); sets the email message
    • if ($this->email->send()) {…} attempts to send the email. If the email is sent successfully, then the message Your Email has successfully been sent else debug information is printed on what might have gone wrong.

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

About Author

Leave a Reply

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

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email