CodeIgniter Basic Tutorial
Performance & Utilities
CodeIgniter Advanced
Sending emails is a very common feature in web applications such as contact forms, registration confirmation, password reset, and notifications.
CodeIgniter provides a powerful Email Class that makes sending emails simple using different protocols like Mail, SMTP, and Sendmail.
Before sending emails, load the email library in your controller:
$this->load->library('email');
You can configure email settings in two ways:
$config['protocol'] = 'smtp'; $config['smtp_host'] = 'ssl://smtp.googlemail.com'; $config['smtp_port'] = '465'; $config['smtp_user'] = 'your_email@gmail.com'; $config['smtp_pass'] = 'your_password'; $config['mailtype'] = 'html'; $config['charset'] = 'utf-8'; $config['newline'] = "\r\n"; $this->email->initialize($config);
application/config/email.php
$config = array( 'protocol' => 'smtp', 'smtp_host' => 'ssl://smtp.googlemail.com', 'smtp_port' => 465, 'smtp_user' => 'your_email@gmail.com', 'smtp_pass' => 'your_password', 'mailtype' => 'html', 'charset' => 'utf-8', 'newline' => "\r\n" );
Then load it with:
$this->load->config('email'); $this->email->initialize($this->config->item());
Create a file application/controllers/EmailController.php
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class EmailController extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('email'); } public function send_email() { // Email configuration $config['protocol'] = 'smtp'; $config['smtp_host'] = 'ssl://smtp.googlemail.com'; $config['smtp_port'] = '465'; $config['smtp_user'] = 'your_email@gmail.com'; $config['smtp_pass'] = 'your_password'; $config['mailtype'] = 'html'; $config['charset'] = 'utf-8'; $config['newline'] = "\r\n"; $this->email->initialize($config); // Sender email $this->email->from('your_email@gmail.com', 'Your Website Name'); // Receiver email $this->email->to('receiver@example.com'); // CC & BCC $this->email->cc('cc@example.com'); $this->email->bcc('bcc@example.com'); // Email subject & message $this->email->subject('CodeIgniter Email Test'); $this->email->message('<h3>This is a test email sent from CodeIgniter.</h3>'); // Send email if ($this->email->send()) { echo "Email sent successfully!"; } else { show_error($this->email->print_debugger()); } } }
You can also attach files before sending:
$this->email->attach('/path/to/file.pdf');
$this->email->mailtype = 'text'; $this->email->message("This is a plain text email.");