Articles: 843 | Categories: 148   
   
   
Home Articles Contact Us
 
 
 
 
Sending Email with AJAX (0 Comments)
Admin: Posted Date: March 3, 2010

As you may have guessed regarding the title, this three-part series explains the development of a fairly simple AJAX-driven email client application, which offers some interesting capabilities for sending email.

Sending Email with AJAX: Interacting with the Server


Here we are again. Welcome to the last tutorial of the series “Sending email with AJAX.” As you may have guessed regarding the title, this three-part series explains the development of a fairly simple AJAX-driven email client application, which offers some interesting capabilities for sending email, as well as for displaying and adding contacts, all without the need to involve page reloads.

Introduction

Recapping from the previous article, let’s go quickly over the explanation of the source code developed so far. As you’ll hopefully remember, in the second tutorial, I wrote the complete set of JavaScript functions –- called the client-side application layer -- in order to provide the program with the ability to request the PHP responsible for sending email messages, along with reading and writing new data to the XML file that stores contact information.

Although the number of defined functions that make up this AJAX application is considerable, fortunately their logic is pretty simple to grasp. Taking into account the underlying ease of the application, you can quickly expand its functionality or improve some of the existing features without having to tackle annoying updating and maintenance issues. As for most open source applications, improvements are always welcome.

Now, returning to this last installment of the series, the next step involved in the creation of the AJAX-based email client rests on writing the corresponding PHP code, which actually takes care of sending email. In order to keep the PHP snippet running fast, all the code I plan to write will be deployed as a procedural script. However, if you’re thinking of including this application as part of a larger web project, you may want to consider developing the server-side code by using an object-oriented approach.

Right, with the preliminaries out of our way, let’s start developing the corresponding PHP snippet for sending email.

Sending Email with AJAX: Interacting with the Server - Sending email with PHP: developing a straightforward script


(Page 2 of 5 )

Anyone who has spent some time programming with PHP knows that by far the easiest way to send email is by using the “mail()” function, and of course, this case won’t be the exception to that rule. Indeed, it’s also possible to send email by utilizing TCP sockets, which can give much more control over each relevant task involved in the whole process, but for meeting the requirements of the AJAX-based application in question, the “mail()” function is more than enough.

Now that you know what approach I’m going to take regarding this crucial topic, have a look at the PHP file below, which sends out email messages:

// clean up POST data
array_map('trim',$_POST);
// check if 'recipient' field has been filled or not
if(!$_POST['to']||$_POST['to']=='TO: '){
    echo 'STATUS: PLEASE SPECIFY AN EMAIL ADDRESS';
    exit();
}
// check if 'subject' field has been filled or not
if(!$_POST['subject']||$_POST['subject']=='SUBJECT: '){
    echo 'STATUS: PLEASE SPECIFY A SUBJECT';
    exit();
}
// check if 'message' field has been filled or not
if(!$_POST['message']){
    echo 'STATUS: PLEASE ENTER YOUR MESSAGE';
    exit();
}
// get message fields
$to=str_replace('TO:','',$_POST['to']);
$subject=str_replace('SUBJECT:','',$_POST['subject']);
$message=$_POST['message'];
// define MIME headers
$headers="MIME-Version 1.0\r\n"."Content-Type: text/plain;
charset=iso-8859-1\r\n"."From:
myaddress@mydomain.com\r\n"."Reply-to:
myaddress@mydomain.com\r\n";
// check if 'CC' field has been filled or not
if(!empty($_POST['cc'])&&$_POST['cc']!='CC: '){
    $headers.="Cc: ".str_replace('CC:','',$_POST['cc'])."\r\n";
}
// check if 'Bcc' field has been filled or not
if(!empty($_POST['bcc'])&&$_POST['bcc']!='BCC: '){
    $headers.="Bcc: ".str_replace('BCC:','',$_POST['bcc'])."\r\n";
}
// send email
if(!mail($to,$subject,$message,$headers)){
    echo 'STATUS: ERROR SENDING MESSAGE';
    exit();
}
else{
    echo 'STATUS: MESSAGE WAS SENT SUCCESSFULLY';
    exit();
}

Admittedly, the script above is extremely easy to follow. As you’ll recall from my previous article, all the data included when sending the pertinent email message is submitted by a regular POST http request, so the script begins cleaning up the respective POST data. In this specific case, I’ve only used the “trim()” PHP built-in function for removing unwanted white space, but you may want to apply a thorough filter on the data, by stripping tags and removing single and double quotes, depending on the configuration of your ”php.ini” file.

The next thing the above script does is sequentially check to see if the “To,” “Subject” and “Message” fields have been filled in, respectively. If any of them hadn’t been populated, the script sends back to the client an indicative error message and program execution is stopped. In addition, as you can see, the email address verification process is kept at a basic level, which returns me to the issue I discussed earlier, since there’s plenty of room to implement more complex routines for checking the validity of entered data. Regarding this checking process, here are the lines that verify whether the pertinent fields have been filled in or not:

// check if 'recipient' field has been filled or not
if(!$_POST['to']||$_POST['to']=='TO: '){
    echo 'STATUS: PLEASE SPECIFY AN EMAIL ADDRESS';
    exit();
}
// check if 'subject' field has been filled or not
if(!$_POST['subject']||$_POST['subject']=='SUBJECT: '){
    echo 'STATUS: PLEASE SPECIFY A SUBJECT';
    exit();
}
// check if 'message' field has been filled or not
if(!$_POST['message']){
    echo 'STATUS: PLEASE ENTER YOUR MESSAGE';
    exit();
}

Now, by continuing with the explanation of each task performed by the script, after having checked input data, it determines whether the corresponding “Cc” and “Bcc” fields have been specified. In that case, they’re appended to the string that composes the MIME headers of the message. This process is conveniently illustrated as follows:

$headers="MIME-Version 1.0\r\n"."Content-Type: text/plain; charset=iso-8859-1
\r\n"."From: myaddress@mydomain.com\r\n"."Reply-to:
myaddress@mydomain.com\r\n";
// check if 'CC' field has been filled or not
if(!empty($_POST['cc'])&&$_POST['cc']!='CC: '){
    $headers.="Cc: ".str_replace('CC:','',$_POST['cc'])."\r\n";
}
// check if 'Bcc' field has been filled or not
if(!empty($_POST['bcc'])&&$_POST['bcc']!='BCC: '){
    $headers.="Bcc: ".str_replace('BCC:','',$_POST['bcc'])."\r\n";
}

Finally, the email message is sent out, as shown below:

// send email
if(!mail($to,$subject,$message,$headers)){
    echo 'STATUS: ERROR SENDING MESSAGE';
    exit();
}
else{
    echo 'STATUS: MESSAGE WAS SENT SUCCESSFULLY';
    exit();

Well, so far I have written a PHP script for sending email, which although simple, is quite useful for my specific purpose of providing the AJAX application with this ability. What’s next? Fortunately, that’s simple to answer. In the next section, I’ll be listing the source code for the PHP snippet that inserts new contacts into the respective XML file, so you can have a clear idea of how the complete server-side layer looks. Thus, clink the link below and keep reading.

Sending Email with AJAX: Interacting with the Server - Getting the server-side application layer completed: listing the “addcontact.php” PHP file



As I previously explained, below is the source code list that corresponds to the “addcontact.php” PHP file, which as you’ll probably recall, is tasked with inserting new nodes into the XML file that stores contact data:

$file='contacts.xml';
array_map('trim',$_POST);
$str='<contact>'."\n".'<name>'.$_POST
['fullname'].'</name>'."\n".'<email>'.$_POST
['email'].'</email>'."\n".'</contact>'."\n".'</contactlist>';
if(!$fp=fopen($file,'r+')){
  trigger_error('Error opening contacts file',E_USER_ERROR);
}
$contents=fread($fp,filesize($file));
rewind($fp);
$contents=str_replace('</contactlist>',$str,$contents);
//header('Content-Type: text/xml');
fwrite($fp,$contents);
fclose($fp);

Is the above PHP script now fresh in your mind? I hope so. Now, let’s complete the server-side application layer, by showing how a sample XML contact file would look:

<?xml version="1.0" encoding="iso-8859-1"?>
<contactlist>
<contact>
<name>Full Name 1</name>
<email>address1@domain1.com</email>
</contact>
<contact>
<name> Full Name 2</name>
<email> address2@domain2.com </email>
</contact>
<contact>
<name> Full Name 3</name>
<email> address3@domain3.com </email>
</contact>
<contact>
<name> Full Name 4</name>
<email> address4@domain4.com </email>
</contact>
<contact>
<name> Full Name 5</name>
<email> address5@domain5.com </email>
</contact>
</contactlist>

All right, at this stage, I think I’ve finished defining the building blocks that comprise the complete server-side layer of my AJAX email application. As you’ve seen, a couple of extendable PHP snippets are all I need to get the program interacting in a seamless way with the server. This should demonstrate that building up this kind of applications isn’t difficult at all.

However, this AJAX-driven email application wouldn’t be complete without listing together both client and server-side layers, which can be quite useful if you want to have the entire source code available in one place. Keeping this in mind, jump into the last two sections of this article, in order to see how the complete AJAX-driven program looks.

Sending Email with AJAX: Interacting with the Server - Putting the layers together: listing the application’s source code, first section


If you feel inclined to copy the complete code of the application and study it, then this is a good time to do precisely that. Here’s the source code for AJAX-driven email client, starting with the “ajaxmail.htm” file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>AJAX-DRIVEN MAIL CLIENT</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-
8859-1">
<script language="javascript">
//*****************************************
//
// Description: Ajax-driven email client
// Author: Alejandro Gervasio
// Version: 1.0
//
//*****************************************
// getXMLHttpRequest object
function getXMLHttpRequestObject(){
    var xmlobj;
    // check for existing requests
    if(xmlobj!=null&&xmlobj.readyState!=0&&xmlobj.readyState!=4){
        xmlobj.abort();
    }
    try{
        // instantiate object for Mozilla, Nestcape, etc.
        xmlobj=new XMLHttpRequest();
    }
    catch(e){
        try{
            // instantiate object for Internet Explorer
            xmlobj=new ActiveXObject('Microsoft.XMLHTTP');
        }
        catch(e){
            // Ajax is not supported by the browser
            xmlobj=null;
            return false;
        }
    }
            return xmlobj;
}
// request 'sendmail.php' file - sends email message
function sendEmailRequest(){
    var message=document.getElementsByTagName('form')[1].elements
['message'].value;
    if(message.length>1000){message=message.substring(0,1000)};
    // open socket connection
    emailXMLHttpObj.open('POST','sendmail.php',true);
    // set form http header
    emailXMLHttpObj.setRequestHeader('Content-
Type','application/x-www-form-urlencoded; charset=UTF-8');
    // get form values and send http request
    emailXMLHttpObj.send(getFormValues
(document.getElementsByTagName('form')[1]));
    emailXMLHttpObj.onreadystatechange=emailStatusChecker;
}
// check status of email requester object
function emailStatusChecker(){
    // if mail request is completed
    if(emailXMLHttpObj.readyState==4){
        if(emailXMLHttpObj.status==200){
            // if status == 200 display server response
            displayServerResponse();
        }
        else{
            alert('Failed to get
response :'+emailXMLHttpObj.statusText);
        }
    }
}


// display server response
function displayServerResponse(){
    var status=document.getElementsByTagName('h1')[1].firstChild;
    if(!status){return};
    // display messages by <h1> header
    status.data=emailXMLHttpObj.responseText; 
}
// get form values
function getFormValues(fobj){
    var str='';
    for(var i=0;i< fobj.elements.length;i++){
        str+=fobj.elements[i].name+'='+ escape(fobj.elements
[i].value)+'&';
    }
    str=str.substr(0,(str.length-1));
    return str;
}          
// get contact list
function getContactList(){
    // request 'contact.xml' file
    contactXMLHttpObj.open('GET','contacts.xml',true);
    contactXMLHttpObj.setRequestHeader('Content-
Type','text/xml');
    contactXMLHttpObj.send(null);
    contactXMLHttpObj.onreadystatechange=contactStatusChecker;
}
// check status of contact requester object
function contactStatusChecker(){
    // if request of 'contacts.xml' file is completed
    if(contactXMLHttpObj.readyState==4){
        if(contactXMLHttpObj.status==200){
            // if status == 200 display contact list
            displayContacts();
        }
        else{
            alert('Failed to get response :'+contactXMLHttpObj.statusText);
        }
    }
}
// display list of contacts
function displayContacts(){
    var
cdiv=document.getElementById('contactlist')?
document.getElementById('contactlist'):document.createElement('div');
    cdiv.setAttribute('id','contactlist');
    // reset contacts container
    cdiv.innerHTML='';
    // read 'contacts.xml' file
    var contacts=contactXMLHttpObj.responseXML.getElementsByTagName
('contact');
    if(!contacts){return};
    var ul=document.createElement('ul');
    for(var i=0;i<contacts.length;i++){
        // create contact links
        var li=document.createElement('li');
        var a=document.createElement('a');
        // get 'email' value
        var email=contacts[i].getElementsByTagName('email')
[0].firstChild.nodeValue;
        // add 'href' attribute
        a.setAttribute('href','#');
        // add 'title' attribute
        a.setAttribute('title',email);
        // add contact labels
        a.appendChild(document.createTextNode(contacts
[i].getElementsByTagName('name')[0].firstChild.nodeValue));
        // fill form fields when contact is clicked on
        a.onclick=function(){fillEmailFields(this.title)};
        li.appendChild(a);
        ul.appendChild(li);
        cdiv.appendChild(ul);
    }
    // append contact links to web document
    document.getElementById('contsection').appendChild(cdiv);
}
// add new contact
function addContact(){
    // create containing div
    var cdiv=document.createElement('div');
    // create 'fullname' field
    var fullname=document.createElement('input');
    fullname.setAttribute('type','text');
    fullname.setAttribute('name','fullname');
    fullname.setAttribute('value','Enter Full Name');
    fullname.className='contfield';
    fullname.onfocus=function(){this.value=''};
    // create 'email' field
    var emailaddr=document.createElement('input');
    emailaddr.setAttribute('type','text');
    emailaddr.setAttribute('name','email');
    emailaddr.setAttribute('value','Enter Email Address');
    emailaddr.className='contfield';
    emailaddr.onfocus=function(){this.value=''};
    // create 'done' button
    var donebtn=document.createElement('input');
    donebtn.setAttribute('type','button');
    donebtn.setAttribute('name','sendcontact');
    donebtn.setAttribute('value','Done');
    donebtn.className='mailbutton';
    // append form fields to containing div
    cdiv.appendChild(fullname);
    cdiv.appendChild(emailaddr);
    cdiv.appendChild(donebtn);
    // get 'addContact" button
    addbtn=document.getElementsByTagName('form')[0].elements
['add'];
    // replace 'addContact' button with div
    addbtn.parentNode.replaceChild(cdiv,addbtn);
    // insert contact into 'contacts.xml' file
    donebtn.onclick=function(){
        insertXMLHttpObj.open('POST','addcontact.php',true);
        // set form http header
        insertXMLHttpObj.setRequestHeader('Content-
Type','application/x-www-form-urlencoded; charset=UTF-8');
        // get form values and send http request
        insertXMLHttpObj.send(getFormValues
(document.getElementsByTagName('form')[0]));
        // replace back containing div with 'addContact" button
        cdiv.parentNode.replaceChild(addbtn,cdiv);
        // refresh contact list
        getContactList();
    }
}
// fill form field with contact values
function fillEmailFields(email){
    var to=document.getElementsByTagName('form')[1].elements
['to'];
    if(!to){return};
    var cc=document.getElementsByTagName('form')[1].elements
['cc'];
    if(!cc){return};
    var bcc=document.getElementsByTagName('form')[1].elements
['bcc'];
    if(!bcc){return};
    if(to.value=='TO: '||!to.value){to.value='TO:
'+email;return};
    if(cc.value=='CC: '||!cc.value){cc.value='CC:
'+email;return};
    if(bcc.value=='BCC: '||!bcc.value){bcc.value='BCC:
'+email;return};
}
// initialize email client
function intitializeEmailClient(){
    if(document.getElementById&&document.
getElementsByTagName&&document.createElement){
        var sendbtn=document.getElementsByTagName('form')
[1].elements['send'];
        if(!sendbtn){return};
        // assign 'onlick' event handler to 'send' button
        sendbtn.onclick=function(){
            // display message
            document.getElementsByTagName('h1')
[1].firstChild.data='STATUS: SENDING MESSAGE...';
            // send email request
            sendEmailRequest();     
        }
        var clearbtn=document.getElementsByTagName('form')
[1].elements['clear'];
        if(!clearbtn){return};
        // assign 'onlick' event handler to 'clear message'
button
        clearbtn.onclick=function(){document.getElementsByTagName
('h1')[1].firstChild.data='STATUS: COMPOSING NEW MESSAGE'};
        var contactbtn=document.getElementsByTagName('form')
[1].elements['contact'];
        if(!contactbtn){return};
        // assign 'onlick' event handler to 'contact' button
        contactbtn.onclick=getContactList;
        var addbtn=document.getElementsByTagName('form')
[0].elements['add'];
        // assign 'onlick' event handler to 'add Contact' button
        addbtn.onclick=addContact;                      
        // display contact list
        getContactList();
    }
}
// instantiate email XMLHttpRequest object
var emailXMLHttpObj=getXMLHttpRequestObject();
// instantiate contact XMLHttpRequest object
var contactXMLHttpObj=getXMLHttpRequestObject();
// instantiate insert XMLHttpRequestObject
var insertXMLHttpObj=getXMLHttpRequestObject();
window.onload=intitializeEmailClient;
</script>
<style type="text/css">
body {
            margin: 0;
            padding: 0;
}
h1 {
            font: bold 16px Arial, Helvetica, sans-serif;
            margin: 5px;
}
a:link,a:visited {
            display: block;
            width: 120px;
            padding: 2px 0 2px 5px;
            font: bold 12px Verdana, Arial, Helvetica, sans-
serif;
            color: #00f;
            text-decoration: none;
            border: 1px solid #cc3;
}
a:hover {
            color: #f33;
            background: #fff;
            border: 1px solid #000;
}
form {
            display: inline;
}
textarea {
            width: 575px;
            height: 380px;
            margin-left: 5px;
            background: #ffc;
            border: 1px solid #000;
}
#container {
            width: 800px;
            height: 572px;
            padding: 5px;
            margin-left: auto;
            margin-right: auto;
            background: #cc9;
            border: 1px solid #000;
}
#mailsection{
            float: left;
            width: 590px;
            height: 570px;
            margin-left: 5px;
            background: #cc3;
            border: 1px solid #000;
}
#contsection {
            float: left;
            width: 200px;
            height: 570px;
            background: #cc3;
            border: 1px solid #000;
            overflow: auto;
}
.mailfield {
            width: 575px;
            height: 20px;
            margin: 0 0 5px 5px;
            border: 1px solid #000;
            background: #ffc;
            font: bold 11px Verdana, Arial, Helvetica, sans-
serif;
            color: #000;
}
.mailbutton {
            width: 120px;
            height: 25px;
            margin-left: 5px;
            font: bold 11px Verdana, Arial, Helvetica, sans-
serif;
            color: #000;
}
.contfield {
            width: 185px;
            height: 20px;
            margin: 0 0px 5px 5px;
            border: 1px solid #000;
            background: #ffc;
            font: bold 11px Verdana, Arial, Helvetica, sans-
serif;
            color: #000;
}
</style>
</head>
<body>
<div id="container">
<div id="contsection">
<h1>CONTACT LIST</h1>
<form>
<input name="add" type="button" value="Add Contact"
class="mailbutton" title="Add new contact" />
</form>
</div>
<div id="mailsection">
<h1>STATUS: COMPOSING NEW MESSAGE</h1>
<form>
<input name="subject" type="text" value="SUBJECT: "
class="mailfield" title="Enter message's subject" />
<input name="to" type="text" value="TO: " class="mailfield"
title="Enter recipient's email address" />
<input name="cc" type="text" value="CC: " class="mailfield"
title="Enter email address for carbon copy" />
<input name="bcc" type="text" value="BCC: " class="mailfield"
title="Enter email address for blind carbon copy" />
<textarea name="message" title="Type your message
here" /></textarea>
<input name="send" type="button" value="Send Message"
class="mailbutton" title="Send Message" />
<input name="clear" type="reset" value="Clear Message"
class="mailbutton" title="Clear Message" />
<input name="contact" type="button" value="Display Contacts"
class="mailbutton" title="Display Contact List" />
</form>
</div>
</div>
</body>
</html>

Sending Email with AJAX: Interacting with the Server - Listing the application's source code, second section




Having listed the (X)HTML file, which runs the corresponding client-side code, here are the pair of PHP files that send email and process contact data, along with a sample contact XML file:

<?php
// ***************************************************
// sendmail.php file - sends email
//
//****************************************************
// clean up POST data
array_map('trim',$_POST);
// check if 'recipient' field has been filled or not
if(!$_POST['to']||$_POST['to']=='TO: '){
    echo 'STATUS: PLEASE SPECIFY AN EMAIL ADDRESS';
    exit();
}
// check if 'subject' field has been filled or not
if(!$_POST['subject']||$_POST['subject']=='SUBJECT: '){
    echo 'STATUS: PLEASE SPECIFY A SUBJECT';
    exit();
}
// check if 'message' field has been filled or not
if(!$_POST['message']){
    echo 'STATUS: PLEASE ENTER YOUR MESSAGE';
    exit();
}
// get message fields
$to=str_replace('TO:','',$_POST['to']);
$subject=str_replace('SUBJECT:','',$_POST['subject']);
$message=$_POST['message'];
// define MIME headers
$headers="MIME-Version 1.0\r\n"."Content-Type: text/plain; charset=iso-8859-1\r\n"."From: myaddress@mydomain.com\r\n"."Reply-to: myaddress@mydomain.com\r\n";
// check if 'CC' field has been filled or not
if(!empty($_POST['cc'])&&$_POST['cc']!='CC: '){
    $headers.="Cc: ".str_replace('CC:','',$_POST['cc'])."\r\n";
}
// check if 'Bcc' field has been filled or not
if(!empty($_POST['bcc'])&&$_POST['bcc']!='BCC: '){
    $headers.="Bcc: ".str_replace('BCC:','',$_POST
['bcc'])."\r\n";
}
// send email
if(!mail($to,$subject,$message,$headers)){
    echo 'STATUS: ERROR SENDING MESSAGE';
    exit();
}
else{
    echo 'STATUS: MESSAGE WAS SENT SUCCESSFULLY';
    exit();
}
?>

<?php
// ***************************************************
// addcontact.php file – adds new contact to XML file
//
//****************************************************
$file='contacts.xml';
$str='<contact>'."\n".'<name>'.$_POST
['fullname'].'</name>'."\n".'<email>'.$_POST
['email'].'</email>'."\n".'</contact>'."\n".'</contactlist>';
if(!$fp=fopen($file,'r+')){
            trigger_error('Error opening contacts
file',E_USER_ERROR);
}
$contents=fread($fp,filesize($file));
rewind($fp);
$contents=str_replace('</contactlist>',$str,$contents);
//header('Content-Type: text/xml');
fwrite($fp,$contents);
fclose($fp);
// sample contact XML file
?>

<?xml version="1.0" encoding="iso-8859-1"?>
<contactlist>
<contact>
<name>Full Name 1</name>
<email>address1@domain1.com</email>
</contact>
<contact>
<name> Full Name 2</name>
<email> address2@domain2.com </email>
</contact>
<contact>
<name> Full Name 3</name>
<email> address3@domain3.com </email>
</contact>
<contact>
<name> Full Name 4</name>
<email> address4@domain4.com </email>
</contact>
<contact>
<name> Full Name 5</name>
<email> address5@domain5.com </email>
</contact>
</contactlist>

Bottom line

After some hard work, this is the end of the series. Over these tutorials, I went through the development of an AJAX-driven email client, by progressively building the JavaScript/(X)HTML layers, as well as coding the respective PHP files that interact with the server. Hopefully, this series has illustrated the particulars of working with multiple http requester objects across a single application, in conjunction with extending a little more the boundaries of your background in AJAX. Now you that have the knowledge and the willpower, start creating AJAX-based applications. It’s really fun!

 
 
Add a Comment:
 
(You must be signed in to comment on an article. Not a member? Click here to register)
   
Title:

Comments: