Working with the Email Class in Code Igniter

Unless you’ve already built a PHP toolkit that lets you develop web applications by reusing its components, the best way to create complex PHP programs quickly is by means of a third-party framework, such as Code Igniter (http://codegniter.com). This package will let you build robust object-based PHP applications in literally minutes, thanks to its extremely friendly interface. So, if you’re interested in learning how to put this framework to work for you, start reading this article now!

Introduction

Welcome to the eighth part of the series titled “Introducing the Code Igniter PHP Framework.” Comprised of nine comprehensive tutorials, this group of articles walks you through learning the main features that come packaged with this PHP-4 based software, and also teaches you how to develop diverse web applications by using the Model-View-Controller approach.

Now that you’ve been introduced to the main subject of the series, it’s time to recapitulate very quickly the topics discussed in the last article. As you’ll possibly remember, in that article I explained how to use the database class that comes bundled with Code Igniter to perform database insertions, updates and deletions via the active record pattern.

In that particular case, all these database-related operations were accomplished without having to code explicitly any SQL statements, which makes web applications more compact and maintainable.

However, Code Igniter comes equipped with so many other useful features, that covering all of them by a few articles is practically impossible. Even so, in this eight chapter of the series, I’ll be providing you with a quick overview on working with its email class, in this manner you can start using it when developing your own PHP applications.

Now, it’s time to continue this educational journey and learn how to send email with Code Igniter. Let’s jump in!

{mospagebreak title=Sending email with Code Igniter}

True to form, sending email through Code Igniter is a process reduced to feeding its email class with some typical parameters, such the email’s sender, the message’s subject, the corresponding text, and so forth. Of course, this has to be done by using the MVC pattern, therefore I’m going to define a controller class that sends email in a truly simple fashion.

The signature of this controller is listed below. Take a look at it, please:

class Email extends Controller{

function Email(){

// load controller parent

parent::Controller();

$this->load->library(‘email’);

}

function index(){

// set email class parameters

$this->email->from(‘me@domain.com’,'Alejandro Gervasio’);

$this->email->to(‘you@domain.com’);

$this->email->cc(‘migirlfriend@domain.com’);

$this->email->bcc(‘myothergirlfriend@domain.com’);

$this->email->subject(‘Testing email class’);

$this->email->message(‘How are you, buddy?’);

$data['title']=’Sending email…’;

$data['header']=’Sending email now…’;

$data['message']=$this->email->send()?’Message was sent successfully!’:'Error sending email!’;

$this->load->view(‘email_view’,$data);

}

}

As you can see, the above “Email” controller class presents a structure similar to the examples developed in previous tutorials. First, its constructor loads the corresponding email class via a loader object, so it can be used at a later time.

Then, the “index()” method sets a few conventional parameters, which are used to send the email message, and finally dispatches the message via the “send()” method. Also, you should notice that the controller uses a view to display an error message or a simple confirmation of whether or not the email has been successfully sent. That was really simple to follow, wasn’t it?

Now that you have learned how to use Code Igniter to send email messages very easily, it’s time to see how to code the previous view file, which will print on screen an indicative message.

To learn how this view file will be created, please click on the link that appears below and keep up reading.

{mospagebreak title=Defining a simple view file}

In the section that you just read, I showed you how to build a basic controller class, which was provided with the capacity to send email messages in a simple fashion. Nonetheless, we need to construct the important part of the program that indicates to the user whether or not the message has been successfully dispatched.

To perform this task, I’m going to create a primitive view file, whose signature will look as simple as this:

<html>

<head>

<title><?php echo $title;?></title>

</head>

<body>

<h1><?php echo $header;?></h1>

<p><?php echo $message;?></p>

</body>

</html>

Undoubtedly, the structure of the view file shown above is extremely simplistic. As you can see, this view, aside from displaying the title along with a simple header, will show an additional message on screen which indicates that the email message has been successfully submitted, or in the worst case, that it failed to be dispatched.

It would also be possible to create two different views, where each of them would be used by the previous controller to display en error string or a confirmation message. However, in this case I decided to code only one view file to keep the example rather simple to follow.

So far, so good. At this point I’ve demonstrated how to use Code Igniter to develop a simple email application, whose structure has been built around the schema imposed by the MVC pattern. So, what comes next?

In the following section I’m going to explain how to take advantage once again of the email class that comes included with Code Igniter. In this case, we’ll build a PHP program that sends email using the data entered in a simple HTML form.

To learn how this sample email application will be developed, you’ll have to click on the link shown below and keep reading.

{mospagebreak title=Sending email messages via an HTML form}

Essentially, the PHP application that I plan to build now will perform really basic tasks, such as sending email by utilizing an HTML form. However, the most interesting facet in developing such a program is that I’m going to combine the functionality of two classes of Code Igniter: the one that sends email, and another one that validates input data.

In addition, I’m going to use the “url” and “form” helper functions that you learned in previous tutorials to dynamically generate certain links. So, having explained how this sample email application is going to work, it’s time to create its first building block, the controller class, whose signature is shown below:   

class Email extends Controller {

function Email(){

// load controller parent

parent::Controller();

// load ‘url’ helper

$this->load->helper(‘url’);

// load ‘form’ helper

$this->load->helper(‘form’);

// load ‘validation’ class

$this->load->library(‘validation’);

// load ‘email’ class

$this->load->library(‘email’);

}

function index(){

// set validation rules

$rules['firstname']="required|min_length[6]|max_length[15]";

$rules['lastname']="required|min_length[6]|max_length[15]";

$rules['email']="required|valid_email";

$this->validation->set_rules($rules);

// set values to repopulate fields

$fields['firstname']=’First Name’;

$fields['lastname']= ‘Last Name’;

$fields['email']=’Email Address’;

$this->validation->set_fields($fields);

// check if user form has been submitted properly

if ($this->validation->run()==FALSE){

// redisplay user form and repopulate fields

$this->load->view(‘form_view’);

}

// display confirmation web page and send email

else{

// set email class settings

$this->email->from($_POST['email'],$_POST['firstname']. ‘ ‘.$_POST['lastname']);

$this->email->to(‘you@domain.com’);

$this->email->cc(‘migirlfriend@domain.com’);

$this->email->bcc(‘myothergirlfriend@domain.com’);

$this->email->subject($_POST['subject']);

$this->email->message($_POST['message']);

$data['title']=’Sending email…’;

$data['header']=’Sending email now…’;

$data['message']=$this->email->send()?’Message was sent successfully!’:'Error sending email!’;

$this->load->view(‘email_view.php’,$data);

}

}

}


Actually, I don’t wan to be excessively optimistic, but in this case the logic implemented by the above “Email” controller is very easy to grasp. As you can see, its constructor begins loading all of the source classes and functions that will be required later on, and this naturally includes all of the classes and helpers that were mentioned previously.

Now, focusing on the implementation of the “index()” method, it’s clear to see that it first sets the validation rules that will be applied to the data entered in the HTML form, then validates this incoming information, and finally submits it via email, assuming that it’s been filled in correctly. Otherwise, the online form will be redisplayed, indicating which entries should be corrected.

As you’ll possibly agree with me, understanding how the above controller class work isn’t something that will make you scratch your head, is it? However, there’s still one step that remains undone if we want to get this email application working as expected.

Yes, you guessed right! In this case, it’s necessary to create the view file that informs users that the HTML form has been submitted successfully. We also need to code the online form that lets them enter their personal information.

So, taking into account those last requirements, here’s the signature of these simple view files:

(definition of ‘email_view.php’ file)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title><?php echo $title;?>title>

</head>

<body>

<h1><?php echo $header;?></h1>

<p><?php echo $message;?></p>

<p><?php echo anchor(‘email’,'Go and submit the form again’);?></p>

</form>

</body>

</html>



(definition of ‘form_view.php’ file)


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Entering user data</title>

<head>

<body>

<h1>Entering user data</h1>

<?php echo $this->validation->error_string;?>

<?php echo form_open(‘email’);?>

<p>First Name <input type="text" name="firstname" value="<?php echo $this->validation->firstname;?>" size="50" /></p>

<p>Last Name <input type="text" name="lastname" value="<?php echo $this->validation->lastname;?>" size="50" /></p>

<p>Email <input type="text" name="email" value="<?php echo $this->validation->email;?>" size="50" /></p>

<p><input type="submit" value="Send Data" /></p>

</form>

</body>

</html>


Here you have it. Assuming that the controller class and the respective view files have been saved to the correct destination folders, the previous email application now should work like a charm. Of course, as I explained in preceding articles, you can test it by typing into your browse the following URL:


http://localhost/codeigniter/index.php/email/


And with this last hands-on example, I’m finishing this overview of building an email application with Code Igniter. As always, feel free to tweak the entirety of the code samples included in this article, so you can improve your skills in using this powerful PHP framework.

Final thoughts

In this eighth part of the series, I explained how to build a web application with Code Igniter that permits users to send email via a simple HTML form. Although this example may seem pretty simplistic, it hopefully will be useful enough to demonstrate how to combine several classes and helpers into one single program.

The last article will be the fruit of the cake, since I’ll be showing you how to use Code Igniter to develop a content management system that will permit you to insert, update and delete information about a collection of movies.

Yes, this time we’re going to Hollywood, so don’t miss the last article!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan