CodeIgniter 4 Send Email with SMTP Tutorial

Share this Article
Reading Time: 9 minutes
348 Views

Sending Emails with SMTP in any application nowadays very common. In CodeIgniter 4, we have in-built Email library class provided. So, inside this article we will see CodeIgniter 4 send email with smtp configuration.

The process of SMTP configuration to send emails is very simple. We need to configure settings and by the help of which we send emails. Let’s see what we need to configure inside codeigniter 4?

For complete CodeIgniter 4 basics please follow this article to get all things clear from basics.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


What is Email Class in CodeIgniter 4?

Email class is a in-built library. There are several features available by the help of which we configure emails. CodeIgniter 4 email class have these 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

Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed.

Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


Turn Development Mode On

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Email library Class in CodeIgniter 4 application

To use Email library class in codeigniter 4 application, we need to do some email configuration at file /app/Config/Email.php

It’s a class file, where we set some values to class member variables.

After doing all needed configuration settings, we load in application like this before use.

$email = \Config\Services::email();

//... rest code for email

Let’s see complete guide for sending emails in codeigniter 4 application.


Settings Email Configuration for SMTP

For email configuration settings, we can use any sending email protocol like mail, sendmail or smtp. Here, we will use SMTP and use Host as Gmail.

Open up the file /app/Config/Email.php. This file is for doing all email settings.

<?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 = "ssl://smtp.gmail.com";

	/**
	 * SMTP Username
	 *
	 * @var string
	 */
	public $SMTPUser = "your_email@gmail.com"; 

	/**
	 * SMTP Password
	 *
	 * @var string
	 */
	public $SMTPPass = "your_smtp_password";

	/**
	 * 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 = 'text';

	/**
	 * 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;

}

Here, inside this file we have configured all basic settings for sending emails. But one more thing before setting your email address and password to a SMTP details. You need to make it as for LESS SECURE APPS AT YOUR GOOGLE ACCOUNT.

When you go at your given email account settings. You will find a Security Tab. When you click into it –

Next, we need to create a method in controller and call Email service.


Load Email Library Class to Send Email

We need to create a controller.

Controller Setup

Open project into terminal and run this spark command to create controller.

$ php spark make:controller User

It will create a file User.php inside /app/Controllers folder. Open file and write this code.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class User extends BaseController
{
    public function sendMail()
    {
        $email = \Config\Services::email(); // loading for use

        // This is for getting form data while submit
        // $to = $this->request->getVar('user_to');
        // $subject = $this->request->getVar('mail_subject');
        // $message = $this->request->getVar('mail_message');

        $email->setTo("to_user@gmail.com");
        $email->setFrom('from_user@gmail.com', 'Confirm Your Email');
        // If you need to send mail to CC and BCC
        // $email->setCC('another@another-user.com');
        // $email->setBCC('other@other-user.com');

        $email->setSubject("Mail subject");
        $email->setMessage("Sample mail message");

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

Now, need to set route to call this controller’s method which sends mail.

Routes Setup

Open Routes.php from /app/Config folder.

//...

$routes->get("send-mail", "User::sendMail");

Application Testing

Open project in terminal and start development server.

$ php spark serve

URL – http://localhost:8080/send-mail

For more details here is the link of Email class library of CodeIgniter 4.

We hope this article helped you to learn CodeIgniter 4 Send Email with SMTP in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

3 thoughts on “CodeIgniter 4 Send Email with SMTP Tutorial”

  1. Hi Sanjay,

    Could you please tell me which code snippet plugin you are using to add code on blog?

    Reply
  2. I do believe all of the ideas you have presented in your post.
    They are really convincing and will definitely work.

    Still, the posts are very quick for beginners. May you please
    extend them a bit from next time? Thank you for the post.

    Reply

Leave a Comment