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--
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.100.180