All Tutorials

Your One-Stop Destination for Learning and Growth

Sending Emails with CodeIgniter: A Step-by-Step Guide

CodeIgniter is a popular open-source PHP framework used for building dynamic websites and web applications. One of its many features is the ease with which you can send emails using the built-in email library. In this tutorial, we'll walk through the process of sending emails using CodeIgniter.

Prerequisites

Before we begin, make sure you have the following prerequisites in place:

  1. A basic understanding of PHP and HTML.
  2. CodeIgniter installed on your local development environment or web server.
  3. A working email account for testing purposes.

Setting Up the Email Configuration

The first step is to configure CodeIgniter's email settings. Open the config/Email.php file and update it with your SMTP email settings:

$config['protocol'] = 'smtp';
$config['smtp_host'] = 'your_smtp_server';
$config['smtp_user'] = 'your_email_address';
$config['smtp_pass'] = 'your_email_password';
$config['smtp_port'] = 'your_smtp_port';
$config['mailtype'] = 'html';

Replace the placeholders with your actual email settings.

Creating the Email Controller

Next, we'll create a new controller named Email.php to handle our email sending functionality:

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

class Email extends CI_Controller {
    public function index() {
        $this->send_email();
    }

    private function send_email() {
        // Send email logic here
    }
}

Writing the Email Logic

Now, we'll add the logic to send emails inside the send_email() method:

private function send_email() {
    $to = 'recipient@example.com';
    $subject = 'Welcome to Our Site!';
    $message = 'Hello, welcome to our site. We are excited that you have joined us and we look forward to helping you in any way we can';

    $this->email->from('sender@example.com', 'Your Name');
    $this->email->to($to);
    $this->email->subject($subject);
    $this->email->message($message);

    if ($this->email->send()) {
        echo 'Email sent.';
    } else {
        show_error('Email could not be sent. Error: ' . $this->email->print_debugger());
    }
}

Replace the placeholders with your actual email details.

Testing Your Email Functionality

With everything set up, it's time to test our email functionality. Navigate to the Email controller by visiting localhost/yourproject/index.php/email in your web browser. If all goes well, you should see the message "Email sent." appear on your screen. To verify that the email has been received, check your recipient's inbox for the message.

Congratulations! You have successfully set up and tested sending emails using CodeIgniter. This is just one of the many features available with this powerful framework, but it's an essential one when working on web applications that require email communication.

Published May, 2016