XML
  Home arrow XML arrow Page 4 - Developing the Server-side Layer of an Ema...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
XML

Developing the Server-side Layer of an Email Application in AJAX
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2006-04-12

    Table of Contents:
  • Developing the Server-side Layer of an Email Application in AJAX
  • Working with a POP3 server: defining the barebones of the "POP3Processor" class
  • Fetching email messages: defining the signature of the "fetch()" method
  • Assembling the POP3 client: putting client and server-side layers to work together

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Developing the Server-side Layer of an Email Application in AJAX - Assembling the POP3 client: putting client and server-side layers to work together


    (Page 4 of 4 )

    As I mentioned before, here's the first file that comprises the web-based POP3 client, "pop_client.htm," which interacts with the "PHP3Processor" class, in order to connect to the POP3 server and retrieve the list of email messages:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <head>
    <title>AJAX-BASED POP3 CLIENT</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-
    8859-1" />
    <script language="javascript">
    var index=0;
    function sendHttpRequest(url,callbackFunc,respXml){
        var xmlobj=null;
        try{
            xmlobj=new XMLHttpRequest();
        }
        catch(e){
            try{
                xmlobj=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e){
                alert('AJAX isn't supported by your browser!');
                return false;
            }
       }
       xmlobj.onreadystatechange=function(){
            if(xmlobj.readyState==4){
                if(xmlobj.status==200){
                    respXml?eval
    (callbackFunc+'(xmlobj.responseXML)'):eval
    (callbackFunc+'(xmlobj.responseText)');
                }
            }
       }
       // open socket connection
       xmlobj.open('POST',url,true);
       // send http header
       xmlobj.setRequestHeader('Content-Type','application/x-www-
    form-urlencoded; charset=UTF-8');
       // get form values and send http request
       xmlobj.send(getFormValues(document.getElementsByTagName
    ('form')[0]));
    }
    // 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;
    }
    // fetch messages from POP3 server
    function fetchMessages(messages){
        // build messages array
        var messages=messages.split('||||');
        var mdiv=document.getElementById('mailcontainer');
        if(!mdiv){return};
        // display mail server response
        mdiv.innerHTML=messages[0];
        // get 'previous' button
        var prev=document.getElementsByTagName('form')[1].elements
    ['prev'];
        if(!prev){return};
        // get 'next' button
        var next=document.getElementsByTagName('form')[1].elements
    ['next'];
        if(!next){return};
        // get 'clear' button
        var clear=document.getElementsByTagName('form')[1].elements
    ['clear'];
        if(!clear){return};
        // move messages pointer back
        prev.onclick=function(){
            index--;
            if(index<0){index=0};
            mdiv.innerHTML=messages[index];
        }
        // move messages pointer forward
        next.onclick=function(){
            index++;
            if(index==messages.length){index=messages.length-1};
            mdiv.innerHTML=messages[index];
        }
        // clear mail container
        clear.onclick=function(){mdiv.innerHTML=''};
    }
    // initialize user panel
    function initializeUserPanel(){
        // get 'connect' button
        var sendbtn=document.getElementsByTagName('form')[0].elements['connect'];
        // send http request when button is clicked on
        sendbtn.onclick=function(){
            // send request & fetch messages from POP3 server
            sendHttpRequest('http://pop_processor.php','fetchMessages');
            // display 'Retrieving...' message
            var mdiv=document.getElementById('mailcontainer');
            if(!mdiv){return};
            mdiv.innerHTML='Retrieving messages from the server...';
        }
    }
    // initialize user panel when page is loaded
    window.onload=function(){
        // check if browser is DOM compatible
        if(document.createElement&&document.getElementById&&document.
    getElementsByTagName){
            // initialize user panel
            initializeUserPanel();
        }
    }
    </script>
    <style type="text/css">
    body {
                margin: 10px 0 0 0;
    }
    #userinfo {
                width: 700px;
                height: 22px;
                padding: 2px 5px 2px 5px;
                border-top: 2px solid #000;
                border-left: 2px solid #000;
                border-right: 2px solid #000;
                background: #9cf;
                margin-left: auto;
                margin-right: auto;
                font: bold 11px Verdana, Arial, Helvetica, sans-
    serif;
                color: #000;
    }
    #mailcontainer {
                width: 700px;
                height: 520px;
                padding: 2px 5px 2px 5px;
                border: 2px solid #000;
                background: #eee;
                margin-left: auto;
                margin-right: auto;
                font: 12px normal Arial, Helvetica, sans-serif;
                color: #000;
                overflow: auto;
    }
    #navbar {
                width: 700px;
                height: 22px;
                padding: 2px 5px 2px 5px;
                border-left: 2px solid #000;
                border-right: 2px solid #000;
                border-bottom: 2px solid #000;
                background: #9cf;
                margin-left: auto;
                margin-right: auto;
    }
    form {
                display: inline;
    }
    .inputbox {
                width: 150px;
                border: 1px solid #000;
                background: #eee;
    }
    .formbutton {
                width: 70px;
                height: 20px;
                font: bold 11px Verdana, Arial, Helvetica, sans-
    serif;
                color: #000;
    }
    </style>
    </head>
    <body>
    <div id="userinfo">
    <form>
    HOST <input name="host" type="text" class="inputbox" title="Enter
    mail hostname" />
    USER <input name="user" type="text" class="inputbox" title="Enter
    username" />
    PASSWORD <input name="pass" type="password" class="inputbox"
    title="Enter password" />
    <input name="connect" type="button" value="Connect"
    class="formbutton" />
    </form>
    </div>
    <div id="mailcontainer">
    </div>
    <div id="navbar">
    <form>
    <input name="prev" type="button" value="&lt;&lt Prev"
    class="formbutton" title="Previous message" />
    <input name="next" type="button" value="Next &gt;&gt;"
    class="formbutton" title="Next message" />
    <input name="clear" type="button" value="Clear"
    class="formbutton" title="Clear all messages" />
    </form>
    </div>
    </body>
    </html>

    And below is the source code that corresponds to the "pop_processor.php" file:

    <?php
    class POP3Processor{
        // declare data members
        private $output='';
        private $fp;
        // constructor
        public function __construct($host,$user,$password){
            if(!$this->fp=fsockopen($host,110,$errno,$errstr,30)){
                throw new Exception('Failed to connect to POP3 server
    '.$errstr.$errno);
            }
            stream_set_timeout($this->fp,2);
            $this->output.=fgets($this->fp,128).'<br />';
            fputs($this->fp,"USER $usern");// send USER command
            $this->output.=fgets($this->fp,128).'<br />';
            fputs($this->fp,"PASS $passwordn");// send PASS command
            $this->output.=fgets($this->fp,128).'<br />';
            $this->output.='||||';// send delimiter string
        }
        // fetch email messages
        public function fetch(){
            fputs($this->fp,"STATn");// send STAT command
            $ret=fgets($this->fp,128).'<br />';
            if(substr($ret,0,5)!='-ERR '){
                $messages=intval(substr($ret,4,1));
                for($i=1;$i<=$messages;$i++){
                    fputs($this->fp,"RETR $in"); // send RETR
    command
                    $this->output.=stream_get_contents($this-
    >fp).'<br /><br />';// fetch email messages
                    $this->output.='||||';// send delimiter string
                }
            }
            $this->output=substr($this->output,0,strlen($this-
    >output)-4);
            return $ret.$this->output;
        }
        // close mail server connection
        public function close(){
            fputs($this->fp,"QUITn");
            fclose($this->fp);
        }
    }
    try{
        // clean up POST data
        array_map('trim',$_POST);
        // instantiate POP3 processor object
        $popProc=new POP3Processor($_POST['host'],$_POST
    ['user'],$_POST['pass']);
        // fetch messages from mail server
        echo $popProc->fetch();
        // close mail server connection
        $popProc->close();
    }
    catch(Exception $e){
        echo $e->getMessage();
        exit();
    }
    ?>

    That's all the source code you need to copy and paste, in order to use the web-based POP3 client. I hope you enjoy the experience!

    To wrap up

    As I said before, we're done now. Over this three-part series I've demonstrated another possible implementation of AJAX, by creating a web-based POP3 client application, handy for retrieving and displaying email messages on a web document. Of course, the program is just a starting point for developing more complex projects, but you should have a clear idea of how to get started using AJAX for building desktop-like applications. Want to know more about web programming? Fine, see you in the next tutorial!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · Over the final installment of this series, the PHP class that talks directly to the...
       · Well written and informative, but it still doesn't work! I copied and pasted the...
       · Thank you for the positive comments on the AJAX-related article I wrote. Regarding...
       · Too bad it still doesn't work for me. Both files are on the same domain, in the same...
       · Hey, thank you for posting your feedback here again. I'm sorry the application is...
       · PHP5 is required.
       · Thank you for posting your feedback here. Yes, you're correct, since the server-side...
       · I have try this application but it did not retrieve any mail message from my inbox....
       · Thank you for commenting on my AJAX article. With reference to your question, you...
       · But when i try using nameko(other application that use php socket),i can retrive the...
       · Can you tell me any mail server that will work with this application?I want to try...
       · Thank you for commenting on my AJAX article again. Unfortunately, I can provide you...
       · I have send you the file..hope you can take a lot and help me on this.By the way I...
       · Thank you for the comments. I alreadly emailed you some source files so you can give...
       · Hai, Any one has idea how to create a web page using strut with ajax.The page...
       · Thank you for commenting on my AJAX article. With reference to your consult, I’ve...
     

    XML ARTICLES

    - Using Regions with XSL Formatting Objects
    - Using XSL Formatting Objects
    - More Schematron Features
    - Schematron Patterns and Validation
    - Using Schematron
    - Datatypes and More in RELAX NG
    - Providing Options in RELAX NG
    - An Introduction to RELAX NG
    - Path, Predicates, and XQuery
    - Using Predicates with XQuery
    - Navigating Input Documents Using Paths
    - XML Basics
    - Introduction to XPath
    - Simple Web Syndication with RSS 2.0
    - Java UI Design with an IDE







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 12 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek