How to Send Emails with CodeIgniter

CodeIgniter is an application development framework that helps PHP developers to create websites faster while avoiding a long time on configuration. It contains a rich set of libraries, including Codeigniter’s email Library, needed for frequent tasks such as an email sender. This article will demonstrate how to set up a CodeIgniter environment and develop a mailer by sending HTML emails, attachments and how to test it with Mailtrap.

Configuration of the development environment

To add more speed to the development process, we can use a Docker image to set up the development environment more quickly, without worrying about installing PHP, database and webserver.

The first step is to install Docker and Docker Compose if you have not already done so. Then, create and access a folder to store the application that will be downloaded in the next steps.

                $ mkdir mailer && cd mailer

Download the docker-compose.yml from Bitnami CodeIgniter Development Container. It is a stable and very useful image that provides a CodeIgniter application and all PHP requirements, including MariaDB.

                $ curl -LO

Now, execute the command below to run the application with Docker:

                $ docker-compose up

The first time it may take a while for Docker to download the dependencies. After application is up, access it via http://localhost:8000 URL. A page similar to the image will appear. If you see it, you can move on to the next steps.

The CodeIgniter application has several folders and files to allow an application to start without the need to add any new code. In our scenario, we need to take a look at config, controllers and views folders located at mailer/myapp/application.

The configfolder contains the configuration information for setting up an email sending and the routes to defining the flow between the actions and pages.

The views folder contains the files with HTML that will be rendered in the browser. And the controllers folder contains the PHP classes with methods that will be executed when called from URL routes.

Defining routes

In the routes.phpadd the line below to inform the application that the new controller will be a standard controller. It means, the index of this controller will be the action called when accessing the application root (/).

                # mailer/myapp/application/config/routes.php

$route['default_controller'] = 'mailer';

Creating the controller

In the controllers folder, create a new file called Mailer.php. This file is an Email controller and extends CI_Controller of the CodeIgniter framework. For now, we will only need two methods, the constructor and the index, to test the route and the connection between the controller and view.

                # mailer/myapp/application/controllers/Mailer.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Mailer extends CI_Controller {
function __construct() {

	public function index() {

Creating a view

In the views folder, create a new folder called mailer. Then, create a new file called form.php. The code below contains a simple page with a form with a field for the email and a submit button. The action on the form will be added later.

                # mailer/myapp/application/views/mailer/form.php

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?><!DOCTYPE html>
<title>Email Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<h1>Sending email</h1>
<form method="post" enctype="multipart/form-data">
<input type="email" id="to" name="to" placeholder="Email">
<input type="submit" value="Send" />

Now, accessing the http://localhost:8000 URL again will show the page with the form that was created right now.

Testing emails with Mailtrap

Before we proceed and create the sending action, we need to set up a way to test whether the sending of email is working. The best way to test email sending is Mailtrap. Mailtrap is an email testing platform that captures SMTP traffic from Staging and Dev environments. It provides a sandbox to test, inspect and debug how our emails will go to the recipient.

Getting credentials

To start, create a Mailtrap account and login. Click on Add Inbox, fill in the inbox name and click on Save. Now, click on the gear icon to see the credentials needed to send email with Mailtrap. On the page where you were redirected, click on Integrations list and choose CodeIgniter to view the configuration code.

In the config folder, create a file called email.php and paste the code shown on the Mailtrap page.

                # mailer/myapp/application/config/email.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');
$config = [
'protocol' => 'smtp',
'smtp_host' => '',
'smtp_port' => 2525,
'smtp_user' => 'your smtp user',
'smtp_pass' => 'your smtp password',
'crlf' => "\r\n",
'newline' => "\r\n"

Sending email

Add the send method to the Mailer controller. It will associate the email configuration created in the previous step, get the email filled in the form and send it to the Mailtrap sandbox. The CodeIgniter’s Email Class is loaded to enable the email send method. It will define Email routes and redirect to the page with a success message or to details on the error page.

                # mailer/myapp/application/controllers/Mailer.php

public function send() {

	$from = '';
	$to = $this->input->post('to');

	$this->email->subject('New email');
$this->email->message('New email received!');

	if ($this->email->send()) {
echo 'Sent with success!';
	} else {

To finish sending our first email, add the action to the form in our Email view created earlier. This will connect the submit button with the send() method on Mailer controller.

                # mailer/myapp/application/views/mailer/form.php

<form method="post" action="mailer/send" enctype="multipart/form-data">

Testing sending

Access the root of the application, fill in the email field and click on the Send button.

Now, go back to your Mailtrap account and check if a new email has arrived.

Sending HTML Email

Allowing sending email with HTML content is very simple, just add a configuration setting the type of content informing that the email will contain HTML tags.

                # mailer/myapp/application/config/email.php

$config = [
  'mailtype' => 'html'

Then, change the content of the email by passing an HTML tag just to test it in Mailtrap.

# mailer/myapp/application/controllers/Mailer.php

$this->email->message("<h1>Welcome, ${to}!!!</h1>");

In Mailtrap, see that the HTML and HTML Source tabs are active.

Sending Emails to Multiple Recipients

CodeIgniter allows you to send email to multiple recipients. This is possible by joining all emails in a single string separating them with a comma or creating an array where each desired email is a new item.

                # mailer/myapp/application/controllers/Mailer.php

# As string

# As array
$to = $this->input->post('to');
$to_other_email = $this->input->post('to_other_email');
$this->email->to([$to, $to_other_email]);

# mailer/myapp/application/views/mailer/form.php

<input type="email" id="to" name="to" placeholder="Email">
<input type="email" id="to_other_email" name="to_other_email" placeholder="Other email">

Check it on Mailtrap!

CC and BCC Emails

The CodeIgniter library offers many facilities, including carbon copy (CC) and blind carbon copy (BCC). To use it, we can pass an email list in a comma-delimited string or an array, just like multiple recipients. See more in the documentation:

                # mailer/myapp/application/controllers/Mailer.php

# As CC

# As BCC

Let’s see if it worked.

We can send files in attachments that can be added to the project or provided by an external URL.

To send a file hosted elsewhere, only the URL of the file is required.

                # mailer/myapp/application/controllers/Mailer.php

# Hosted elsewhere

To send a file hosted in the application, you will need to create a folder and add the file there. The full path can be retrieved by the DOCUMENT_ROOT variable concatenated with the file name.

                # New folder images
# New file image.png
# myapp/application/images/image.png

# Hosted in application
$attached_file= $_SERVER["DOCUMENT_ROOT"]."/application/images/image.png";

Check one last time.

CodeIgniter sounds like an easy to set up framework and with a low learning curve. It’s easy to learn quickly even for developers coming from other languages and familiar with other MVC frameworks like Ruby on Rails and Django.

Docker proves once again that it is an excellent tool to help you start learning new technologies faster while avoiding unnecessary worries and problems with development environments.

Mailtrap is a service that saves time for testing emails. It allows you to inspect HTML codes, provides spam reporting and a lot of technical information even for free accounts. Using it in the development environment is a faster and better approach compared with the configuration of local SMTP servers and spamming the personal inbox.

Finally, be open to new attempts and try to do the same thing in different ways. It is a good way to improve your skills and strengthen your knowledge.

I hope you enjoyed reading our guide on CodeIgniter email library that was originally published on Mailtrap Blog.

Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies and get more readers

Join other developers and claim your FAUN account now!




Total Hits