18 min read

There might be times rather than just plain text, so you may wish to include images, text formatting, and URLs in the body of your e-mail. HTML e-mails will allow you to do this and CodeIgniter Email library can easily be set to do just that.

How to do it…

HTML e-mails can be sent by executing the following steps:

  1. Create a file email.php at /path/to/codeigniter/application/controllers/.
  2. Add the following code to the controller file 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'] = 'html'; $this->email->initialize($config); $this->email->from('[email protected]', 'Your Name'); $this->email->to('[email protected]'); $this->email->subject('This is a html email'); $html = 'This is an <b>HTML</b> email'; $this->email->message($html); $this->email->send(); echo $this->email->print_debugger(); } }

How it works…

In the constructor controller we load the Email library (highlighted in the following code), which provides support for us 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'] = 'html';

Here, we’re telling CodeIgniter to send the e-mail as HTML rather than as text.

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 using the following code:

$this->email->send();

If all works out as planned, you should see an output similar to the following code:

Your message has been successfully sent using the following protocol: sendmail User-Agent: CodeIgniter Date: Fri, 4 Oct 2013 08:56:59 +0200 From: "Your Name" <[email protected]> Return-Path: <[email protected]> To: [email protected] Subject: =?iso-8859-1?Q?This_is_a_html_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: multipart/alternative; boundary="B_ALT_524e66bbf2868" This is a multi-part message in MIME format. Your email application may not support this format. --B_ALT_524e66bbf2868 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit This is an HTML email --B_ALT_524e66bbf2868 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable This is an <b>HTML</b> email --B_ALT_524e66bbf2868--

Sending attachments with CodeIgniter Email

There might be times when you wish to send an attachment along with the e-mail, such as an invoice to a customer for a recent purchase or perhaps an image. The CodeIgniter Email library can easily be set to do just that.

How to do it…

You can send attachments with CodeIgniter Email by executing the following steps:

  1. Create a file email.php at /path/to/codeigniter/application/controllers/.
  2. Add the following code to the controller file, 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'] = 'html'; $this->email->initialize($config); $this->email->from('[email protected]', 'Your Name'); $this->email->to('[email protected]'); $this->email->subject('This is a html email'); $html = 'This is an <b>HTML</b> email with an attachment, <i>lovely!</i>'; $this->email->message($html); $this->email->attach('/path/to/attachment'); $this->email->send(); echo $this->email->print_debugger(); } }

How it works…

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 the CodeIgniter Email library to work with, such as the system used to send the e-mail (in this case, sendmail), the path to send mail on your system, the mailtype variable (text or HTML), and so on. These configuration settings are initialized (that is, passed to the Email library) and we begin to build the e-mail; setting the to, from, subject, and message attributes, as well as the path to the attachment we’re sending in the e-mail (highlighted in the following code):

$this->email->from('[email protected]', 'Your Name'); $this->email->to('[email protected]'); $this->email->subject('This is a html email'); $html = 'This is an <b>HTML</b> email with an attachment, <i>lovely!</i>'; $this->email->message($html); $this->email->attach('/path/to/attachment');

Then, send the e-mail using the following code:

$this->email->send();

Sending bulk e-mails with CodeIgniter Email

There may be times when you wish to send out bulk e-mails; perhaps to all the people who have paid to go on a tour. You may wish to send them each a personalized e-mail, and also add an attachment. You may also want to pull their e-mail preference (plain text or HTML) from the account on your database and send them the correct format of e-mail. That’s what we’re going to do here.

Getting ready

We need to know each person’s preferences such as whether they want HTML e-mails or text, and also their individual reference number (or booking ID) for their trip. As per this requirement, we are going to have a database to hold all the information; so copy the following code into your database:

CREATE TABLE `bookers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(50) NOT NULL, `lastname` varchar(50) NOT NULL, `email` varchar(255) NOT NULL, `email_pref` varchar(4) NOT NULL, `booking_ref` varchar(10) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; INSERT INTO `bookers` (`id`, `firstname`, `lastname`, `email`, `email_pref`, `booking_ref`) VALUES (1, 'Robert', 'Foster', '[email protected]', 'html', 'ABC123'), (2, 'Lucy', 'Welsh', '[email protected]', 'html', 'DEF456');

How to do it…

  1. Create a file email.php at /path/to/codeigniter/application/controllers/.
  2. Add the following code to the controller file, 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; $query = "SELECT * FROM bookers "; $result = $this->db->query($query); foreach ($result->result() as $row) { $this->email->clear(); if ($row->email_pref == 'text') { $config['mailtype'] = 'text'; $body = 'Hi ' . $row->firstname . ', Thanks you for booking with us, please find attached the itinerary for your trip. This is your booking reference number: ' . $row->booking_ref . ' Thanks for booking with us, have a lovely trip.'; } else { $config['mailtype'] = 'html'; $body = 'Hi ' . $row->firstname . ',<br /><br />Thanks you for booking with us, please find attached the itinerary for your trip. </p>This is your booking reference number: <b>' . $row->booking_ref . '</b><br /><br />Thanks for booking with us, have a lovely trip.'; } $this->email->initialize($config); $this->email->to($row->email); $this->email->from('[email protected]'); $this->email->subject('Holiday booking details'); $this->email->message($body); $this->email->send(); } echo $this->email->print_debugger(); } }

How it works…

In the constructor controller we load the Email library (highlighted in the following code), which provides support for us 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 mail from your system.

We then query the database for each of the customer’s booking details:

$query = "SELECT * FROM bookers "; $result = $this->db->query($query); foreach ($result->result() as $row) { }

The query will loop through each result and send a specific e-mail based on the values retrieved from the database in each loop.

Firstly, we give ourselves a clean slate by clearing all the settings and variables from a previous loop iteration by using the CodeIgniter email function:

$this->email->clear();

We then look at their e-mail preference and set the e-mail sending (mailtype) variable accordingly, along with the text for the body of the e-mails. So, if someone prefers HTML, we look for that preference and define the body of the HTML e-mail, otherwise for a text e-mail, we look for the text e-mail preference and define the body for the text e-mail:

if ($row->email_pref == 'text') { $config['mailtype'] = 'text'; $body = 'Hi ' . $row->firstname . ', Thank you for booking with us, please find attached the itinerary for your trip. This is your booking reference number: ' . $row->booking_ref . ' Thanks for booking with us, have a lovely trip.'; } else { $config['mailtype'] = 'html'; $body = 'Hi ' . $row->firstname . ',<br /><br />Thank you for booking with us, please find attached the itinerary for your trip. </p>This is your booking reference number: <b>' . $row->booking_ref . '</b><br /><br />Thanks for booking with us, have a lovely trip.'; }

After this, we initialize the configuration variables. Those of you who have looked at the previous few recipes will notice that the initialization takes place later in the code of this recipe than in others. This is because we cannot initialize the config variables earlier as some of the variables rely on the preferences of individual customers, which are fetched from the database. So, we have to wait until each user’s details are fetched from a database to initialize each iteration of the configuration settings. And finally, we send the e-mail:

$this->email->send();

If all goes well, you should see an output similar to the following:

Your message has been successfully sent using the following protocol: sendmail User-Agent: CodeIgniter Date: Fri, 4 Oct 2013 20:06:13 +0200 To: [email protected] From: <[email protected]> Return-Path: <[email protected]> Subject: =?iso-8859-1?Q?Holiday_booking_details?= 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: multipart/alternative; boundary="B_ALT_524f0395942bb" This is a multi-part message in MIME format. Your email application may not support this format. --B_ALT_524f0395942bb Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Hi RobertThanks you booking with us, please find attached the itinerary for your trip. This is your booking reference number: ABC123 Thanks for booking with us, have a lovely trip. --B_ALT_524f0395942bb Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable Hi Robert<br /><br />Thanks you booking with us,=20 please find attached the itinerary for your trip. </p>This is your booking reference number:=20 <b>ABC123</b><br /><br /> Thanks for booking with us, have a lovely trip. --B_ALT_524f0395942bb--

Using an HTML table with DataTable

DataTable is a free to use library that turns your normal looking html table into an interactive marvel with sortable and searchable columns and a whole lot more; we’re going to use it with CodeIgniter, merging DataTable and CodeIgniter table functionality. It’s simple to use and is able to handle most of the things you will need it for. Here, in this recipe, we’re going to use it with DataTable to create an interactive HTML table that is sortable and searchable. It has pagination too! If you want database results, move on to the next recipe, Using an HTML table with DataTable and a database, where we’ll look at populating a table from a database query.

Getting ready

For this recipe, you will need to follow the given procedure:

  1. Ensure that you’ve downloaded DataTable from the following link: https://datatables.net/download/
  2. Unzip the downloaded .zip file, and move the files to a location on your web server or localhost, which will be accessible by CodeIgniter. For this recipe, I have put the folder at application/views; but you can make your own choice if you wish.

How to do it…

  1. Create four files as given:
    • /path/to/codeigniter/application/controllers/table.php
    • /path/to/codeigniter/application/views/table_header.php
    • /path/to/codeigniter/application/views/table_body.php
    • /path/to/codeigniter/application/views/table_footer.php
  2. Create the controller file, table.php, and add the following code to it:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Table extends CI_Controller { function __construct() { parent::__construct(); $this->load->library('table'); } public function index() { $tmpl = array ( 'table_open' => '<table border="0" cellpadding="4" cellspacing="0" id="example">', 'heading_row_start' => '<tr>', 'heading_row_end' => '</tr>', 'heading_cell_start' => '<th>', 'heading_cell_end' => '</th>', 'row_start' => '<tr>', 'row_end' => '</tr>', 'cell_start' => '<td>', 'cell_end' => '</td>', 'row_alt_start' => '<tr>', 'row_alt_end' => '</tr>', 'cell_alt_start' => '<td>', 'cell_alt_end' => '</td>', 'table_close' => '</table>' ); $this->table->set_template($tmpl); $this->table->set_heading(array('ID', 'First Name', 'Last Name')); $this->table->add_row(array('1', 'Rob', 'Foster')); $this->table->add_row(array('2', 'Lucy', 'Welsh')); $this->table->add_row(array('3', 'George', 'Foster')); $this->table->add_row(array('4', 'Jackie', 'Foster')); $this->table->add_row(array('5', 'Antony', 'Welsh')); $this->table->add_row(array('6', 'Rowena', 'Welsh')); $this->table->add_row(array('7', 'Peter', 'Foster')); $this->table->add_row(array('8', 'Jenny', 'Foster')); $this->table->add_row(array('9', 'Oliver', 'Welsh')); $this->table->add_row(array('10', 'Felicity', 'Foster')); $this->table->add_row(array('11', 'Harrison', 'Foster')); $this->table->add_row(array('12', 'Mia', 'The Cat')); $data['table'] = $this->table->generate(); $this->load->view('tables/table_header'); $this->load->view('tables/table_body',$data); $this->load->view('tables/table_footer'); } }

  3. Create the view file, table_header.php, and add the following code to it:

    <html> <head> <style type="text/css" title="currentStyle"> @import "<?php echo $this->config->item('base_url') ; ?>application/views/DataTables-1.9.4/media/css/demo_page.css"; @import "<?php echo $this->config->item('base_url') ; ?>application/views/DataTables-1.9.4/media/css/jquery.dataTables.css"; </style> <script type="text/javascript" language="javascript" src="<?php echo $this->config->item('base_url') ; ?>application/views/DataTables-1.9.4/media/js/jquery.js"></script> <script type="text/javascript" language="javascript" src="<?php echo $this->config->item('base_url') ; ?>application/views/DataTables-1.9.4/media/js/jquery.dataTables.js"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#example').dataTable(); } ); </script> </head> <body>

    Take a look at the <script> tag:

    <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#example').dataTable(); } ); </script>

    The #example parameter is the ID of the table (detailed in the following How it works… section). Ensure that the value example in <script> and table markup is the same.

  4. Create the view file, table_body.php, and add the following code to it:

    <?php echo $table ; ?>

  5. Create the controller file, table_footer.php, and add the following code to it:

     

    </body> </html>

How it works…

The constructor in the table controller loads the CodeIgniter’s Table library:

function __construct() { parent::__construct(); $this->load->library('table'); }

The public function index() function is called. We then define how we want our HTML table markup to appear. This is where you can place any markup for the specific CSS, using which you can style the elements of the table:

$tmpl = array ( 'table_open' => '<table border="0" cellpadding="4" cellspacing="0" id="example">', 'heading_row_start' => '<tr>', 'heading_row_end' => '</tr>', 'heading_cell_start' => '<th>', 'heading_cell_end' => '</th>', 'row_start' => '<tr>', 'row_end' => '</tr>', 'cell_start' => '<td>', 'cell_end' => '</td>', 'row_alt_start' => '<tr>', 'row_alt_end' => '</tr>', 'cell_alt_start' => '<td>', 'cell_alt_end' => '</td>', 'table_close' => '</table>' );

Take a closer look at the table_open element of the $tmpl array. Look for the item highlighted in the preceding code. The id=”example” item is used by DataTable (in the <script> tag of the file table_header.php) to apply its CSS and functionality. You can, of course, name it anything you like, but be sure to reflect that change in the JavaScript.

We then call $this->table->set_template() to apply the HTML table markup:

$this->table->set_template($tmpl);

We then set the table headers and apply the data for our rows. Ensure that the number of items in the table headers is the same as the number of items in the table data:

$this->table->set_heading(array('ID', 'First Name', 'Last Name')); $this->table->add_row(array('1', 'Rob', 'Foster')); $this->table->add_row(array('2', 'Lucy', 'Welsh')); $this->table->add_row(array('3', 'George', 'Foster')); $this->table->add_row(array('4', 'Jackie', 'Foster')); $this->table->add_row(array('5', 'Antony', 'Welsh')); $this->table->add_row(array('6', 'Rowena', 'Welsh')); $this->table->add_row(array('7', 'Peter', 'Foster')); $this->table->add_row(array('8', 'Jenny', 'Foster')); $this->table->add_row(array('9', 'Oliver', 'Welsh')); $this->table->add_row(array('10', 'Felicity', 'Foster')); $this->table->add_row(array('11', 'Harrison', 'Foster')); $this->table->add_row(array('12', 'Mia', 'The Cat'));

We then generate the table. The $this->table->generate() function will return a string of HTML, which we save in $data[‘table’].

$data['table'] = $this->table->generate();

The $data array our view files for rendering to the browser:

$this->load->view('tables/table_header'); $this->load->view('tables/table_body',$data); $this->load->view('tables/table_footer');

LEAVE A REPLY

Please enter your comment!
Please enter your name here