Sending Emails in Codeigniter

Sending Emails With Codeigniter is very Easy. First We Have To Load Email library


Then We Have To Set Email Parameters

We Have To Setup Several Functions including From() function takes two parameters the email address of the sender and the name. to() function takes the email address of the recipient. Next two functions are subject() and message() that round up the requirements for sending emails in CodeIgniter. Here is how these functions are used in the code:

  1. $this->email->from('[email protected]', 'Identification');
  2. $this->email->to('[email protected]');
  3. $this->email->subject('Send Email Codeigniter');
  4. $this->email->message('The email send using codeigniter library');
  1. $this->email->send();

Create the Controller

Create a controller file Sendingemail_controller.php and save it in the application/controller/. Add the following code to this file:

  1. class Sendingemail_Controller extends CI_Controller {
  2. function __construct() {
  3. parent::__construct();
  4. $this->load->library('session');
  5. $this->load->helper('form');
  6. }
  7. public function index() {
  8. $this->load->helper('form');
  9. $this->load->view('contact_email_form');
  10. }
  11. public function send_mail() {
  12. $from_email = "[email protected]";
  13. $to_email = $this->input->post('email');
  14. //Load email library
  15. $this->load->library('email');
  16. $this->email->from($from_email, 'Identification');
  17. $this->email->to($to_email);
  18. $this->email->subject('Send Email Codeigniter');
  19. $this->email->message('The email send using codeigniter library');
  20. //Send mail
  21. if($this->email->send())
  22. $this->session->set_flashdata("email_sent","Congragulation Email Send Successfully.");
  23. else
  24. $this->session->set_flashdata("email_sent","You have encountered an error");
  25. $this->load->view('contact_email_form');
  26. }
  27. }
  28. ?>

Create the View

Create a view file called contact_email_form.php and save it in application/views/. Add the following code to it:

  1. Send Email Codeigniter
  2. echo $this->session->flashdata('email_sent');
  3. echo form_open('/Sendingemail_Controller/send_mail');
  4. ?>
  5. "email" name = "email" required />
  6. "submit" value = "SEND MAIL">
  7. echo form_close();
  8. ?>

Make the changes in the routes.php file in application/config/routes.php and add the following line at the end of the file:

  1. $route['email'] = 'Sendingemail_Controller';

Access the Email Application

Finally, Hit the following URL to access the application:


Setting SMTP Configuration

As mentioned earlier, CodeIgniter fully supports different email protocols including SMTP through simple configuration options.

As you could see from the following code snippet, selecting the email protocol is the matter of setting a single configuration variable. In this code snippet, I have set the $config[‘protocol’] to  smtp for using SMTP protocol.;