How to Send Email using CodeIgniter

โšก Smart Summary

CodeIgniter Sending Email relies on the framework’s built-in Email library to deliver messages through SMTP or the local mail server. This example creates an email config file, a contact form view, and a controller that reads form input and dispatches the message.

  • ๐Ÿ“ง Built-in Library: The Email library sends mail with minimal code and supports SMTP, Sendmail, and PHP mail transports.
  • โš™๏ธ Central Config: A custom email.php config file stores the protocol, host, port, user, and password so settings stay in one place.
  • ๐Ÿ”“ SMTP Credentials: Valid smtp_host, smtp_user, and smtp_pass values are required; dummy parameters will never deliver a real email.
  • ๐Ÿ“ Form to Controller: A contact view collects the recipient, subject, and message, which the controller reads with the input library.
  • ๐Ÿ“ค Send Flow: The controller sets from, to, subject, and message, then calls send() and prints a debugger report on failure.
  • ๐Ÿ“Ž HTML and Files: Switching mailtype to html and calling attach() lets you send formatted messages with file attachments.
  • ๐Ÿค– AI Assist: AI tools can generate the email controller, validate form input, and diagnose SMTP connection errors from the debugger output.

CodeIgniter Sending Email

Email is very important in web applications. When a user signs up, we might want to send them an email to verify their email address and allow the user to confirm the subscription. We also use email to reset forgotten passwords and send invoices and receipts to customers. CodeIgniter makes it super easy for us to send emails from our application using a variety of options.

CodeIgniter has a built-in email library that we can work with when sending emails.

CodeIgniter Email Configuration

We need to have a central place where we can manage the email settings. CodeIgniter does not come with a config file for emails, so we will have to create one ourselves.

Create a file email.php in the directory application/config

Add the following code to email.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');
 
$config = array(
'protocol' => 'smtp', // 'mail', 'sendmail', or 'smtp'
'smtp_host' => 'smtp.example.com',
'smtp_port' => 465,
'smtp_user' => 'no-reply@example.com',
'smtp_pass' => '12345!',
'smtp_crypto' => 'ssl', //can be 'ssl' or 'tls' for example
'mailtype' => 'text', //plaintext 'text' mails or 'html'
'smtp_timeout' => '4', //in seconds
'charset' => 'iso-8859-1',
'wordwrap' => TRUE
);

HERE,

  • ‘protocol’ => ‘smtp’, specifies the protocol that you want to use when sending email. This could be Gmail SMTP settings or SMTP settings from your host
  • ‘smtp_host’ => ‘smtp.example.com’, specifies the SMTP host. For example, if you want to use Gmail then you would have something like smtp.gmail.com
  • ‘smtp_port’ => 465, an open port on the specified SMTP host that has been configured for SMTP mail
  • ‘smtp_user’ => ‘no-reply@example.com’, the email address that will be used as the sender when sending emails. This should be a valid email address that exists on the server
  • ‘smtp_pass’ => ‘12345!’, the password to the specified SMTP user email
  • ‘smtp_crypto’ => ‘ssl’, specifies the encryption method to be used, i.e. ssl, tls etc.
  • ‘mailtype’ => ‘text’, sets the mail type to be used. This can be either plain text or HTML depending on your needs.
  • ‘smtp_timeout’ => ‘4’, specifies the time in seconds that should elapse when trying to connect to the host before a timeout exception is thrown.
  • ‘charset’ => ‘iso-8859-1’, defines the character set to be used when sending emails.
  • ‘wordwrap’ => TRUE, if set to TRUE then word-wrap is enabled. If it is set to FALSE, then word-wrap is not enabled

Note: for sending emails to work, you should provide valid configuration parameters. Dummy parameters will not be able to send emails.

CodeIgniter Email View

In this section, we will create the view that will send the email to the recipient.

Create a new directory email in application/views

Create a new file contact.php in application/views/email

Add the following code to application/views/email/contact.php

<!DOCTYPE html>
<html>
<head>
<title>CodeIgniter Send Email</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>
<h3>Use the form below to send email</h3>
<form method="post" action="<?=base_url(0)?>" enctype="multipart/form-data">
<input type="email" id="to" name="to" placeholder="Receiver Email">
<br><br>
<input type="text" id="subject" name="subject" placeholder="Subject">
<br><br>
<textarea rows="6" id="message" name="message" placeholder="Type your message here"></textarea>
<br><br>
<input type="submit" value="Send Email" />
</form>
</div>
</body>
</html>

HERE,

  • We have a basic HTML form that accepts the email, subject and message, then passes the parameters to the email route.

CodeIgniter Email Controller

Let us now create the controller that will be handling sending email.

Create a new file EmailController.php in application/controllers/EmailController.php

Add the following code to EmailController.php

<?php
 
defined('BASEPATH') OR exit('No direct script access allowed');
 
class EmailController extends CI_Controller {
 
public function __construct() {
parent:: __construct();
 
$this->load->helper('url');
}
 
public function index() {
$this->load->view('email/contact');
}
 
function send() {
$this->load->config('email');
$this->load->library('email');
 
$from = $this->config->item('smtp_user');
$to = $this->input->post('to');
$subject = $this->input->post('subject');
$message = $this->input->post('message');
 
$this->email->set_newline("\r\n");
$this->email->from($from);
$this->email->to($to);
$this->email->subject($subject);
$this->email->message($message);
 
if ($this->email->send()) {
echo 'Your Email has successfully been sent.';
} else {
show_error($this->email->print_debugger());
}
}
}

HERE,

  • class EmailController extends CI_Controller {…} defines our email controller that extends the parent CodeIgniter controller.
  • public function __construct() {…} defines the child constructor that calls the parent constructor method.
  • public function index() {…} defines the index method that displays the contact form
  • function send() {…} defines the method that sends the email
    • $this->load->config(’email’); loads the email configuration settings
    • $this->load->library(’email’); loads the email library
    • $from = $this->config->item(‘smtp_user’); gets the sender id from the email configuration file that we defined.
    • $to = $this->input->post(‘to’); gets the to value from the submitted form
    • $subject = $this->input->post(‘subject’); sets the email subject from the form
    • $message = $this->input->post(‘message’); sets the email message from the form
    • $this->email->set_newline(“\r\n”); defines the new line characters for emails
    • $this->email->from($from); sets the sender email address
    • $this->email->to($to); sets the recipient email address
    • $this->email->subject($subject); sets the email subject
    • $this->email->message($message); sets the email message
    • if ($this->email->send()) {…} attempts to send the email. If the email is sent successfully, then the message “Your Email has successfully been sent” is shown, else debug information is printed on what might have gone wrong.

Let us now define the email routes.

Email Routes

Add the following routes to application/config/routes.php

$route['send-email'] = 'EmailController';
$route['email'] = 'EmailController/send';

We can now load the contact form in the web browser.

Let us start the built-in PHP server.

Open the terminal or command line and browse to the root of your application. In my case, the root is located in drive C:\Sites\ci-app

cd C:\Sites\ci-app

Start the server using the following command

php -S localhost:3000

Load the following URL in your web browser: http://localhost:3000/send-email

You should be able to see the following form

Email Routes

Enter the recipient email, subject, and email message, then click on Send Email. If your email configuration is set properly, then you should be able to see the success message.

How to Send HTML Emails and Attachments in CodeIgniter

The same Email library can send richly formatted messages and files. Two small changes turn the plain-text example above into an HTML email with an attachment.

$this->email->set_mailtype('html');
$this->email->message('<h3>Welcome</h3><p>Thanks for joining us.</p>');
$this->email->attach('/path/to/report.pdf');
  • set_mailtype(‘html’): tells the library the body contains HTML, so tags such as headings and links render in the recipient’s inbox.
  • attach(): adds a file from a server path to the message; call it once for each file before send().

Remember that HTML emails should still include a plain-text alternative, and large attachments may be rejected by strict mail servers.

FAQs

Localhost usually has no mail server, so the mail protocol fails silently. Switch the protocol to smtp and supply a real SMTP host, user, and password, or use a service such as Mailtrap for local testing.

Set smtp_host to smtp.gmail.com, smtp_port to 465 with ssl, and smtp_user to your Gmail address. Use a Google App Password rather than your normal password, since Gmail blocks basic password logins.

The mail protocol uses PHP’s mail() function, sendmail calls the server’s local binary, and smtp connects to an external mail server with credentials. SMTP is the most reliable for delivery and authentication.

Yes. AI can build the controller, add form validation for the recipient and subject, and include success and error handling. Review the SMTP settings and add rate limiting before using it in production.

Yes. Paste the output of print_debugger(), and AI can interpret SMTP handshake failures, authentication errors, or port issues, then recommend the corrected host, port, or encryption values to try.

Summarize this post with: