It's always useful to be able to send e-mails and CodeIgniter comes with an excellent library for sending e-mails. There are a few recipes in this chapter, which deal with sending e-mails. However, this is the basic Hello World type example that is very simple.
A simple way to send plain e-mails using CodeIgniter Email is as follows:
email.php
at path/to/codeigniter/application/controllers/
.email.php
:<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'), class Email extends CI_Controller { function __construct() { parent::__construct(); $this->load->helper('url'), $this->load->library('email'), } public function index() { redirect('email/send_email'), } public function send_email() { $config['protocol'] = 'sendmail'; $config['mailpath'] = '/usr/sbin/sendmail'; $config['charset'] = 'iso-8859-1'; $config['wordwrap'] = TRUE; $config['mailtype'] = 'text'; $this->email->initialize($config); $this->email->from('[email protected]', 'Your Name'), $this->email->to('[email protected]'), $this->email->subject('This is a text email'), $this->email->message('And this is some content for the text email.'), $this->email->send(); echo $this->email->print_debugger(); } }
In the constructor controller we load the Email library (highlighted in the following code), which provides support to send e-mails:
function __construct() {
parent::__construct();
$this->load->helper('url'),
$this->load->library('email'),
}
Next, public function index()
redirects us to the function public function send_mail()
, which sets some initial configuration variables for CodeIgniter Email library to work with, such as the system used to send the e-mail (in this case, sendmail
), the path to send e-mail on your system, the
mailtype
variable (text or HTML), and so on. Take a look at the following line of code:
$config['mailtype'] = 'text';
Here, we're telling CodeIgniter to send the e-mail as just plain text rather than HTML.
These configuration settings are initialized (that is, passed to the Email library), and we begin to build the e-mail by setting the to
, from, subject
, and message
attributes:
$this->email->from('[email protected]', 'Your Name'), $this->email->to('[email protected]'), $this->email->subject('This is a text email'), $this->email->message('And this is some content for the text email.'),
Then, send the e-mail:
$this->email->send();
If all works out as planned, you should see an output similar to the following one:
User-Agent: CodeIgniter Date: Fri, 4 Oct 2013 08:51:03 +0200 From: "Your Name" <[email protected]> Return-Path: <[email protected]> To: [email protected] Subject: =?iso-8859-1?Q?This_is_a_text_email?= Reply-To: "[email protected]" <[email protected]> X-Sender: [email protected] X-Mailer: CodeIgniter X-Priority: 3 (Normal) Message-ID: <[email protected]> Mime-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit And this is some content for the text email.
3.137.192.3