This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How to Send Email in CodeIgniter 4 with SMTP (Step-by-Step Guide)

Updated on September 26, 2025

5 Min Read
codeigniter send email

Key Takeaways

  • SMTP ensures reliable email delivery by using authentication and encryption, unlike PHP’s basic mail() function which often fails on servers.
  • CodeIgniter 4 simplifies email handling with its built-in Email library, so you can integrate SMTP without writing low-level code.
  • Combining CodeIgniter with SMTP gives you a clean, secure, and flexible way to send emails for sign-ups, password resets, or app notifications.

Sending emails is one of those features that almost every app needs – whether it’s for user sign-ups, password resets, or just notifications. In this tutorial, I’ll walk you through how I set up email sending in CodeIgniter 4 using SMTP with Mailtrap.

We’ll go step by step, starting from scratch, so by the end you’ll have a working project where you can test sending emails right from your local machine.

But before we dive into the tutorial, I’ll quickly cover what SMTP is and why CodeIgniter makes email handling easier, so you have the full context.

What is SMTP?

SMTP stands for Simple Mail Transfer Protocol. It’s the standard protocol that email servers use to send and receive messages across the internet. Instead of relying on PHP’s built-in mail() function (which often fails due to server restrictions), SMTP ensures your emails are delivered more reliably, with proper authentication and encryption.

Why Use CodeIgniter for Email?

CodeIgniter 4 comes with a built-in Email library, which makes handling SMTP a lot easier. You don’t have to worry about writing raw SMTP commands or dealing with complicated configurations.

With just a few settings in your Email.php config file and some simple controller logic, you can send fully functional emails in minutes.

Building the Email Feature in CodeIgniter 4

Now that we understand the basics, let’s roll up our sleeves and set up email sending in CodeIgniter 4 using SMTP.

Prerequisites

Here’s what I have set up on my machine (make sure you’ve got these too):

  • Windows 10
  • XAMPP Control Panel v3.3.0 (Apache + PHP 8.2)
  • Composer 2.8+
  • A free Mailtrap account (we’ll use this to safely test emails)

Step 1: Create a New CodeIgniter Project

Fire up the XAMPP Control Panel and start the Apache server.

XAMPP Control Panel

Open CMD and move into your htdocs folder inside XAMPP:

cd C:\xampp\htdocs

Now let’s create a fresh CodeIgniter project (I’ll name mine ci4-smtp-demo, but you can pick another name if you prefer):

composer create-project codeigniter4/appstarter ci4-smtp-demo

composer create-project codeigniter4

Once installed, test it by visiting:

http://localhost/ci4-smtp-demo/public/

You should see the default CodeIgniter welcome page.

default CodeIgniter welcome page

Step 2: Configure .env

In your project folder, rename the file .env.example.env.

Open it and update these lines:

CI_ENVIRONMENT = development

app.baseURL = 'http://localhost/ci4-smtp-demo/public/'

Configure .env

💡 Tip: If you named your project something else, make sure to update the path above accordingly.

Step 3: Set Up Mailtrap SMTP

Now we’ll grab SMTP details from Mailtrap.

  • Log into your Mailtrap account.
  • Go to: Sandboxes My SandboxIntegration SMTP tab.

Sandboxes → My Sandbox → Integration → SMTP tab

  • Copy the credentials shown there (host, port, username, password).

They’ll look something like this (your username and password will be different):

Host: sandbox.smtp.mailtrap.io

Port: 2525

Username: YOUR_MAILTRAP_USERNAME

Password: YOUR_MAILTRAP_PASSWORD

Open app/Config/Email.php and update the SMTP section like this:

public string $fromEmail  = '[email protected]';     // replace with your "from" email

public string $fromName   = 'My CI4 App';           // replace with your app name

public string $protocol   = 'smtp';

public string $SMTPHost   = 'sandbox.smtp.mailtrap.io';

public string $SMTPUser   = 'YOUR_MAILTRAP_USERNAME';  // replace with your Mailtrap username

public string $SMTPPass   = 'YOUR_MAILTRAP_PASSWORD';  // replace with your Mailtrap password

public int    $SMTPPort   = 2525;                      // you can also use 465 or 587

public string $SMTPCrypto = '';

public string $mailType   = 'html';

public string $charset    = 'utf-8';

Step 4: Create a Mail Controller

Inside app/Controllers/, create a file called MailController.php and add this code:

Create a Mail Controller

<?php namespace App\Controllers;

use App\Controllers\BaseController;

class MailController extends BaseController
{
    public function index()
    {
        return view('email_form');
    }

    public function send()
    {
        $request = service('request');
        $to      = $request->getPost('to');                               // recipient email
        $subject = $request->getPost('subject') ?? 'Test Email';
        $message = $request->getPost('message') ?? 'Hello from CodeIgniter 4!';

        $email = \Config\Services::email();
        $email->setTo($to);
        $email->setSubject($subject);
        $email->setMessage($message);

        if ($email->send()) {
            return view('email_success');
        } else {
            echo '<pre>';
            print_r($email->printDebugger(['headers']));
            echo '</pre>';
        }
    }
}

Step 5: Create the Views

We’ll make two simple views inside app/Views/.

Create the Views

email_form.php

<!doctype html>
<html>
<head><title>Send Email</title></head>
<body>
  <h1>Send Email</h1>
  <form method="post" action="<?= site_url('mail/send') ?>">
    <label>Recipient Email:</label><br>
    <input type="email" name="to" placeholder="[email protected]" required><br><br>

    <label>Subject:</label><br>
    <input type="text" name="subject" placeholder="Enter subject"><br><br>

    <label>Message:</label><br>
    <textarea name="message" rows="6" placeholder="Write your message here"></textarea><br><br>

    <button type="submit">Send</button>
  </form>
</body>
</html>

email_success.php

<!doctype html>
<html>
<head><title>Email Sent</title></head>
<body>
  <h1>✅ Email sent successfully!</h1>
  <p>Check your Mailtrap inbox to see the message.</p>
  <a href="<?= site_url('mail') ?>">Send another email</a>
</body>
</html>

Step 6: Add Routes

Open app/Config/Routes.php and add:

$routes->get('mail', 'MailController::index');

$routes->post('mail/send', 'MailController::send');

Test It Out

Now go to:

http://localhost/ci4-smtp-demo/public/mail

Fill in the form, hit Send, and if all goes well you’ll see the success page. Head over to your Mailtrap Sandbox inbox, and your test email will be there waiting.

Mailtrap Sandbox inbox

Wrapping Up!

That’s it — we just built a fully working CodeIgniter 4 email sender using SMTP and Mailtrap.

The great thing about this setup is you can safely test emails locally without worrying about spamming real inboxes. When you’re ready to go live, just swap out the Mailtrap credentials with your production SMTP provider (like Gmail, SendGrid, or Amazon SES).

Stop Wasting Time on Servers

Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy.

If you have any questions or confusion, let me know in the comments.

Frequently Asked Questions

Q1. How do I configure SSL/TLS encryption for SMTP in CodeIgniter 4?

You configure SSL/TLS encryption by setting the $SMTPCrypto property in app/Config/Email.php to 'ssl' or 'tls', and ensuring the corresponding $SMTPPort is correct (usually 465 for SSL or 587 for TLS). This secures the connection between your application and the mail server.

Q2. How can I send an email with an attachment in CodeIgniter 4?

You send an email with an attachment by using the $email->attach() method, providing the full file path, before calling $email->send(). For example: $email->attach(FCPATH . 'document.pdf');. This method handles adding the file to the outgoing message.

Q3. What does the CodeIgniter Email Debugger output mean when an email fails to send?

The Email Debugger output shows the conversation with the SMTP server. A failure usually points to: Authentication Failure (Code 535), meaning incorrect username or password; or a Connection Refused error, indicating an incorrect host/port or firewall issue. Examine the “SMTP Command/Data” section for the precise error code.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Abdul Rehman

Abdul is a tech-savvy, coffee-fueled, and creatively driven marketer who loves keeping up with the latest software updates and tech gadgets. He's also a skilled technical writer who can explain complex concepts simply for a broad audience. Abdul enjoys sharing his knowledge of the Cloud industry through user manuals, documentation, and blog posts.

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour