Codeigniter 4 Send Email with SMTP Tutorial with Example

Last updated on by Digamber
In this tutorial, we will learn how to Send an email in CodeIgniter 4 from the localhost using a built-in email library.

Be it personal or professional life, sending the email is a usual work as well as daily work. Luckily, Sending emails to any email client is possible with Codeigniter. It also makes this task super easy for you with its very own prebuilt Email Library.

The email sending process is easy, and you have to correctly configure the Codeigniter’s Email library in your CI 4 application. While configuring Mail settings, you must take care of all the imperatives. The assortment of parameters should be placed at the right place for which it is defined.

Sending an Email is required in web and mobile applications, especially when you:

  • Create a new account
  • Confirm newsletter subscription
  • Send newsletter
  • Reset or change password
  • Send bills or receipts

Codeigniter integrated email system supports the easiness, and this is what it set out to do so. CodeIgniter’s robust Email Class supports the following features:

  • Multiple Protocols: Mail, Sendmail, and SMTP
  • TLS and SSL Encryption for SMTP
  • Multiple recipients
  • CC and BCCs
  • HTML or Plaintext email
  • Attachments
  • Word wrapping
  • Priorities
  • BCC Batch Mode, enabling large email lists to be broken into small BCC batches.
  • Email Debugging tools

You can also check out the full mail preferences list here. Codeigniter can help you send email from your application with its built-in Email library. Let us find out how.

Install Codeigniter

Run the following command to install the CodeIgniter application using composer package.

composer create-project codeigniter4/appstarter

Soon after the download process is done, rename the CI 4 project folder. Such as codeigniter-send-email.

Then, propel yourself inside inside the project directory.

cd codeigniter-send-email

Enable CI Errors

To easily debug the application, we will enable the error reporting in our Codeigniter app.

Open app/Config/Boot/development.php file and set the display_errors to 1 instead of 0. Do the same thing in app/Config/Boot/production.php file.

ini_set('display_errors', '1');

Setting Up SMTP Email Configuration in CodeIgniter

To send emails using SMTP, open app/config/Email.php and add valid configuration parameters in it. We have updated the Email Credentials for Gmail.

<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;

class Email extends BaseConfig
{

	/**
	 * @var string
	 */
	public $fromEmail;

	/**
	 * @var string
	 */
	public $fromName;

	/**
	 * @var string
	 */
	public $recipients;

	/**
	 * The "user agent"
	 *
	 * @var string
	 */
	public $userAgent = 'CodeIgniter';

	/**
	 * The mail sending protocol: mail, sendmail, smtp
	 *
	 * @var string
	 */
	public $protocol = 'smtp';

	/**
	 * The server path to Sendmail.
	 *
	 * @var string
	 */
	public $mailPath = '/usr/sbin/sendmail';

	/**
	 * SMTP Server Address
	 *
	 * @var string
	 */
	public $SMTPHost = 'smtp.googlemail.com';

	/**
	 * SMTP Username
	 *
	 * @var string
	 */
	// Enter your email id from where you send email
	public $SMTPUser = 'test@gmail.com';
	

	/**
	 * SMTP Password
	 *
	 * @var string
	 */
	// Enter your email's password
	public $SMTPPass = 'xxxxxxxxxxx';

	/**
	 * SMTP Port
	 *
	 * @var integer
	 */
	public $SMTPPort = 465;

	/**
	 * SMTP Timeout (in seconds)
	 *
	 * @var integer
	 */
	public $SMTPTimeout = 60;

	/**
	 * Enable persistent SMTP connections
	 *
	 * @var boolean
	 */
	public $SMTPKeepAlive = false;

	/**
	 * SMTP Encryption. Either tls or ssl
	 *
	 * @var string
	 */
	public $SMTPCrypto = 'ssl';

	/**
	 * Enable word-wrap
	 *
	 * @var boolean
	 */
	public $wordWrap = true;

	/**
	 * Character count to wrap at
	 *
	 * @var integer
	 */
	public $wrapChars = 76;

	/**
	 * Type of mail, either 'text' or 'html'
	 *
	 * @var string
	 */
	public $mailType = 'html';

	/**
	 * Character set (utf-8, iso-8859-1, etc.)
	 *
	 * @var string
	 */
	public $charset = 'UTF-8';

	/**
	 * Whether to validate the email address
	 *
	 * @var boolean
	 */
	public $validate = false;

	/**
	 * Email Priority. 1 = highest. 5 = lowest. 3 = normal
	 *
	 * @var integer
	 */
	public $priority = 3;

	/**
	 * Newline character. (Use “\r\n” to comply with RFC 822)
	 *
	 * @var string
	 */
	public $CRLF = "\r\n";

	/**
	 * Newline character. (Use “\r\n” to comply with RFC 822)
	 *
	 * @var string
	 */
	public $newline = "\r\n";

	/**
	 * Enable BCC Batch Mode.
	 *
	 * @var boolean
	 */
	public $BCCBatchMode = false;

	/**
	 * Number of emails in each BCC batch
	 *
	 * @var integer
	 */
	public $BCCBatchSize = 200;

	/**
	 * Enable notify message from server
	 *
	 * @var boolean
	 */
	public $DSN = false;
}

Update Gmail Security Rules

We will send email from localhost using Gmail, so we have to make a little change in Gmail account.

In your Gmail account, click on Manage your Google Account link.

Next, click on the Security.

Codeigniter Send Email with Gmail

Then, turn less secure app access to ON.

Email Send in Codeigniter

Create Controller

Create a new SendMail.php Controller file in app/Controllers folder. Afterwards, incorporate the following code inside the SendMail.php file.

<?php 
namespace App\Controllers;
use App\Models\FormModel;
use CodeIgniter\Controller;

class SendMail extends Controller
{

    public function index() 
	{
        return view('form_view');
    }

    function sendMail() { 
        $to = $this->request->getVar('mailTo');
        $subject = $this->request->getVar('subject');
        $message = $this->request->getVar('message');
        
        $email = \Config\Services::email();

        $email->setTo($to);
        $email->setFrom('johndoe@gmail.com', 'Confirm Registration');
        
        $email->setSubject($subject);
        $email->setMessage($message);

        if ($email->send()) 
		{
            echo 'Email successfully sent';
        } 
		else 
		{
            $data = $email->printDebugger(['headers']);
            print_r($data);
        }
    }

}

Create Routes

To create route add the given below code in app/Config/Routes.php file.

$routes->get('/', 'SendMail::index');

Create View

Create app/Views/form_view.php file and add the following code in it. It will display a form, by filling this from we can send the email with specific message to provided email id.

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Codeigniter 4 Send Email with SMTP - positronx.io</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
  <style>
    .container {
      max-width: 550px;
    }
  </style>
</head>

<body>
  <div class="container mt-5">

    <form method="post" action="<?php echo base_url('SendMail/sendMail') ?>">
      <div class="form-group">
        <label>Receiver Email</label>
        <input type="text" name="mailTo" class="form-control">
      </div>
       
      <div class="form-group">
        <label>Your Subject</label>
        <input type="text" name="subject" class="form-control">
      </div>

      <div class="form-group">
        <label>Message</label>
        <textarea rows="6" type="text" name="message" class="form-control"></textarea>
      </div>

      <div class="form-group">
        <button type="submit" class="btn btn-primary btn-block">Submit</button>
      </div>
    </form>

  </div>
</body>

</html>

CodeIgniter Send Email from Localhost Example

To send email from localhost in Codeigniter we must start the application. So, run the command to start the application:

php spark serve

Enter the following URL in the browser to send the email:

http://localhost:8080

Download the complete code of this tutorial from GitHub.