Site icon RemoteStack

How to Send Email using SMTP in Codeigniter 4 Application

Today, in this quick Codeigniter SMTP tutorial, we will show you how to send emails from localhost to the server in Codeigniter 4 application using the Email class and SMTP settings.

Sending email with SMTP in Codeigniter 4 is not that tough; it requires a systematic approach and some code organization, and you are ready to send the email.

CodeIgniter offers a solid Email Class, which comes with numerous features, like:

PHP CodeIgniter 4 Send Email with SMTP Example

Download Codeigniter Project

In the first section, you will see couple of tips to download the fresh Codeigniter app.

You can click here to download latest version of the Codeigniter app.

You can install the Composer app on your local computer and run the provided command to install the Codeigniter project.

composer create-project codeigniter4/appstarter

Add Email Details in Codeigniter

In this step you need to add the email details in the primary Email.php file, As you can see, there are tons of variables, but you have to look for $SMTPUser and $SMTPPass, add the email credentials like email and password.

Update the email details in the app/config/Email.php file.

<?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
	public $SMTPUser = 'test@gmail.com';
	

	/**
	 * SMTP Password
	 *
	 * @var string
	 */
	// Enter password
	public $SMTPPass = '***********';

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

Register Controller

Next, get inside the app/Controllers/ folder, create a brand new controller file.

Create a couple of functions like index() and send(), the send function uses email() service to send mail, make sure to pass the email.

Open the file and insert the given code in app/Controllers/EmailController.php.

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

class EmailController extends Controller
{

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

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

        $email->setTo($to);
        $email->setFrom('yoda@startrek.com', 'Do you confirm?');
        
        $email->setSubject($subject);
        $email->setMessage($message);

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

}

Create Route

In this section, you need to open app/Config/Routes.php file, set the default route and a new route which will initialize the methods defined in the controller.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->setDefaultController('EmailController');
$routes->get('/send-smtp-mail', 'EmailController::index');
$routes->match(['get', 'post'], 'EmailController/send', 'EmailController:: send');

Formulate View File

Now, the route and controller have been formed; in this step, we have to take care of view, you have to create a view file; in this file, you need to create a form that will send the mail using the SMTP settings.

After creating file, please update the given code in the app/Views/index.php file.

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

<head>
  <meta charset="utf-8">
  <title>Codeigniter 4 SMTP Email Sending Example</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .container {
      max-width: 500px;
    }
  </style>
</head>

<body>
  <div class="container">
    <form method="post" action="<?php echo base_url('EmailController/send') ?>">
      <div class="mb-3">
        <label>Receiver Mail</label>
        <input type="text" class="form-control" name="mail_to">
      </div>
       
      <div class="mb-3">
        <label>Subject</label>
        <input type="text" class="form-control" name="subject">
      </div>

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

      <div class="mb-3">
        <button type="submit" class="btn btn-dark">Send</button>
      </div>
    </form>
  </div>
</body>

</html>

Turn on ‘less secure apps’

You can turn on ‘less secure apps’ settings as mail domain Administrator.

Here is the process to turn on ‘less secure apps’ settings as mailbox user.

Run App in Browser

To run app in the browser, you have to first run the app’s development server, use the suggested command to evoke the process.

php spark serve

Here is the final url that will allow you to view the app on the browser.

http://localhost:8080/send-smtp-mail

Conclusion

We saw how to use the email class and configure it in the controller file to send the mail. We gave you the basic idea of the email class. However, there are other different preferences available to customize how you sent emails in Codeigniter.

Exit mobile version