Building the Index Page for a PHP Email Application

In this third part of a four-part article series on building a PHP email application, we will look at the index page. This page is the heart of the application. We will also look at how to handle attachments in a message and how to integrate them into this application.

The login system that we created in the previous article sends the user through to the index page. This page then downloads the messages from the server and displays its headers. The login script also sends the user ID, which is stored in a session variable called $_SESSION['userid']. In this article we will discuss the work done by the index page as well as the pages to which it links. We will also take a brief look at attachments.

Below is a screen shot of the index page:

Index page

The index page displays the newly downloaded messages in a table with five columns. These columns list (among other things) the date, subject and from field of the messages. There are three things that happen in this script. First the mail connection details of the logged-in user are retrieved:

<?php
session_start();
include("connect.php");
//get popserver login credentials
$query_details = "SELECT * FROM user WHERE user_id = ‘".$_SESSION
['userid']."’";
$result_details = mysql_query($query_details);
$num_details = mysql_num_rows($result_details);
if($num_details > 0 ){
while($res = mysql_fetch_array($result_details)){
$pop = $res['pop3'];
$usname = $res['remuser'];
$pw = $res['rempass'];
$email = $res['email'];
$user = $res['user_id'];
global $email;
}
}else{
echo mysql_error();
}

Then based on the user details, the code moves on to make the connection to the mail server and stores the number of retrieved mail messages in the $numEmails variable:

if($num_details >0){
//put popserver details in headers array
            $mbox = "{".$pop.":110/pop3}INBOX";
            $userid = "$usname";
            $userpassword = "$pw";
            if(!$stream = imap_open($mbox, $userid,
$userpassword)){
            $streamerror = "Connection to server failed";
}
            if(!$headers = @imap_headers($stream)){
            $header = "No!";
            }else{
            $numEmails = sizeof($headers);
}
}
?>

Next, the table is created and the menu and navigation panels are displayed. The navigation panel contains links to the Calendar, Contacts and profile pages. I also attached the user_id variable, which will be used to retrieve the items specific to the user in each of the above folders to the links. When a user clicks on any of these links, they will be taken to the appropriate page:

<table width="100%" border="0" cellspacing="1" class="block">
  <tr class="table">
    <td width="15%" class="table"><a href="NewMsg.php?uid=<?
=$_SESSION['userid'];?>" class="menu">New Message </a></td>
    <td width="15%"><a href="contacts.php?uid=<?=$_SESSION
['userid'];?>" class="menu">Contacts</a></td>
    <td width="12%"><a href="showcal.php?uid=<?=$_SESSION
['userid'];?>" class="menu">Calendar</a></td>
    <td width="46%"><a href="profile.php?uid=<?=$_SESSION
['userid'];?>" class="menu">Profile </a></td>
    <td width="4%">&nbsp;</td>
    <td width="4%">&nbsp;</td>
    <td width="4%">&nbsp;</td>
  </tr>
</table>
<!– InstanceEndEditable –></td>
  </tr>
  <tr>
    <td width="11%" valign="top"><!– InstanceBeginEditable
name="EditRegion4" –>
      <table width="100%" border="0" cellpadding="2"
cellspacing="1" class="block">
        <tr>
          <td class="table"><strong>Folders:</strong></td>
        </tr>

{mospagebreak title=Navigation and Headers}

Next the navigation menu is created and the Inbox, Sent, Trash and Drafts page links are added, all of which will list the number of items contained within them:

  <tr>
          <td class="table"><a href="index.php?uid=<?=$_SESSION
['userid'];?>" class="menu">Inbox</a>(<? if(isset($numEmails)){
                          echo "($numEmails)";} ?>)</td>
        </tr>
        <tr>
          <td class="table"><a href="sent.php" class="menu">Sent
(<? $query_sent = "select * from sent WHERE userid = ‘".$_SESSION
['userid']."’";
            $re = mysql_query($query_sent);
            $num = mysql_num_rows($re);
            if($num > 0){echo $num;}else{echo 0;}?>)</a></td>
        </tr>
        <tr class="table">
          <td class="menu"><a href="drafts.php"
class="menu">Drafts(<? $query_msgs = "select * from drafts WHERE
userid = ‘".$_SESSION['userid']."’";
            $res= mysql_query($query_msgs);
            $n = mysql_num_rows($res);
            if($n > 0){
            echo $n;}else{echo 0;}?>)</a></td>
        </tr>
        <tr>
          <td class="table"><a href="trash.php"
class="menu">Trash(<? $query_trash = "select * from trash WHERE
userid = ‘".$_SESSION['userid']."’";
            $result = mysql_query($query_trash);
            $num_trash = mysql_num_rows($result);
            if($num_trash > 0){
            echo $n_trash;}else{echo 0;}?>)</a></td>
        </tr>
      </table>

Next, a table is created to display the column headers in which the message headers will be displayed. These headers are From, Subject, Date and Action:

                  <table width="100%" border="0" cellpadding="0"
cellspacing="1" class="block">
        <tr class="table">
        <td width="7%" class="listtop">Status</td>
          <td width="22%" valign="top" class="listtop">From</td>
          <td width="38%" valign="top"
class="listtop">Subject</td>
          <td width="22%" valign="top" class="listtop">Date</td>
          <td width="11%" valign="top"
class="listtop">Action</td>
        </tr>

The code below shows how the actual messages are downloaded from the mail server and inserted directly into the database:

<? //if there are new msgs, get them
            if(isset($numEmails) &&($numEmails > 0)) {
            for($i = 1; $i < $numEmails+1; $i++)
{
            $mailHeader = @imap_headerinfo($stream, $i);
            $from = $mailHeader->fromaddress;
            $subject = strip_tags($mailHeader->subject);
            $msgNo = imap_msgno( $stream, $i);
            $date = $mailHeader->date;
            list($dayName,$day,$month,$year,$time) = split("
",$date); 
                        $time = substr($time,0,5);
            $date = $day ."- ". $month ."- ". $year . " ". $time;
            $dates = $year ."- ". $month ."- ". $day;
/*
If you are going to implement attachment handling, this will be a
good place to place your code. It will also be a good place to
place your insert query code. See the attachments section below
for a fuller explanation.
*/
//put messages in db
            include "connect.php";
            $query = "INSERT INTO messages SET msg_num =
‘$msgNo’, from = ‘$from’,subject = ‘$subject’,";
            $query .= "msg_body = ‘$msg_body’, checked =
‘0’,msg_date = ‘$dates’, userid = ‘$user’";
            mysql_query($query);

When the newly downloaded messages are inserted in to the database, the checked column in the messages table is set to zero(0). This makes it easy to differentiate between old and new messages. You can also use the date to differentiate between old and new messages.

{mospagebreak title=Retrieving Messages} 

Next, the messages are retrieved from the database to be displayed in the table:

//get them out and display
//ALL newly downloaded messages will have checked set to 0
            $query_msgs = "select * from messages WHERE checked =
‘0’";
            $re = mysql_query($query_msgs);
            $n = mysql_num_rows($re);
            if($n > 0){
            while($r = mysql_fetch_array($re)){  
?> <td></td>
  <td valign="top" class="list"><? if($r['checked']==1){?>
            <a href="view.php?mid=<?=$r['msg_id'];?>"
class="email2"><?=$r['from']; ?></a>
                                    <? }else{ ?> 
            <a href="view.php?mid=<?=$r['msg_id'];?>&em=<?
$email; ?>" class="email"><?=$r['from'];?></a>
                          <? } ?> </a></td>
          <td valign="top" class="list"><?=$r['subject']; ?></td>
          <td valign="top" class="list"><?=$r['date']; ?></td>
          <td valign="top" class="list"><a href="#"
class="menu">Delete</a></td>
        </tr>
                        <? }
                        }?>
<?
}//end for
}//end check

If there are no new messages, in other words, the $numEmails variable is zero, then the script retrieves the old messages stored in the database:

else{//there are no new messages, so get the old messages from database
?>                    
                        <?
            include "connect.php";
$query_email = "SELECT user_id FROM user WHERE user_id = ‘".$_SESSION['userid']."’";
$result_email= mysql_query($query_email);
$num_email= mysql_num_rows($result_email);
if($num_email > 0 ){
while($res = mysql_fetch_array($result_email)){
$user = $res['user_id'];          
}
}else{
echo mysql_error();
}          
//get all msgs
            $query_msgs = "select * from messages";
            $re = mysql_query($query_msgs);
            $n = mysql_num_rows($re);
            if($n > 0){
            while($r = mysql_fetch_array($re))
{
?>
<tr class="td">
<td><? if($r['checked']==1){?> <img src="images/env.gif" />
<? }else{ ?>
<? echo $r['checked'];}?>
</td>
          <td valign="top" class="list"><? if($r['checked']==1){?>
                                    <a href="view.php?mid=<?=$r
['msg_id'];?>" class="email2"><?=$r['from']; ?></a>
                                    <? }else{ ?> 
                        <a href="view.php?mid=<?=$r['msg_id'];?>"
class="email"><?=$r['from'];?></a>
                          <? } ?> </a></td>
          <td valign="top" class="list"><?=$r['subject']; ?></td>
          <td valign="top" class="list"><?=$r['msg_date']; ?
></td>
          <td valign="top" class="list"><a href="delete.php?
mid=<?=$['msg_id']?>" class="menu">Delete</a></td>
        </tr>
<?
}//end 2nd while
}
}

Last but not least, I’ve made this code available to the script as optional, because you might want to delete all the messages from the mail server after inserting them into the database. This will save you from downloading the same messages when you return to the index page:

/*
//delete emails from server
if($numEmails > 0){
$num_msg = imap_num_msg($stream);
for ( $i=1; $i<=$num_msg; $i++ ) {
   imap_delete($stream, $i);
  }
imap_expunge($stream);
*/
?>
   </table>

{mospagebreak title=Attachments}

An email message often has a couple of parts in it. I will not go into what they all are, but if there is more than one part, then there is a good chance that the message contains at least one attachment. Then all we have to do is download the attachment(s). 

To find an attachment in an email message, first determine the number of parts in the message. If the message contains more than one part, start to search for the attachment and then save it to file when you find it:

<?
//fetch the message parts
$msgparts=imap_fetchstructure($stream,$mID);
   /*
Find the part type, remember that Text is the first type in the
body type table:
0 Text  
1 Multipart
etc
So we are looking for non text type…
*/
   if ($msgparts->type!=0){ 
       if ($msgparts->encoding==3){
$msgparts=base64_decode($msgparts);
 }
/*You need to search two objects here, both return a “attribute” and “value” properties in the arrays:
dparameters
parameters.
The attribute and value properties will contain the file name of the attachments if any.
*/       
 //find the filename in dparameters object if any..     
       if ($msgparts->dparameters>0){
           foreach ($msgparts ->dparameters as $dparam){
            if ($dparam->attribute==

There are two things that you should do if you choose to implement attachment handling in this application. First you need to create a table that will take the name of the attachment (in the form of a link), the messageID of the message tow which the attachment belongs, and finally the user id. You create a separate table for attachments because one message can have more than one attachment, otherwise you would just put the attachment name in the messages table.

Second, you need to add the attachment code just before you insert the newly downloaded messages in the database. That is also the point at which you should insert the attachment data.

delete.php –  The delete page just removes a message from the database and the returns the user to the index page. To delete only the message that we want, we use the msg_id that is passed by the index page:

<?
if(isset($_GET['mid'])){
$query="DELETE from messages WHERE msg_id=’".$_GET['mid']."’";
mysql_query($query);
header("location:index.php");
}
?>

view.php –  The view page enables you to read the entire email message that is retrieved from the database. You are presented with a table that shows all the headers and the message body. You also have the opportunity to reply to the message. In addition, the page includes all the application folders and navigation that you get on the index page:

First, a dynamic table is built to display the various message headers and body  retrieved from the database:

 if($n){
                         while($r = mysql_fetch_array($re)){
                         ?>
        <tr>
          <td width="10%" class="view">From</td>
          <td width="90%" class="td"><?=$r['from']; ?></td>
        </tr>
        <tr>
          <td class="view">To</td>
          <td class="td"><? echo  $email; ?></td>
        </tr>
        <tr>
          <td class="view">Subject</td>
          <td bgcolor="#FFFFFF" class="td"><?=$r['subject']; ?
></td>
        </tr>
        <tr>
          <td class="view">Date</td>
          <td bgcolor="#FFFFFF" class="td"><?=$r['msg_date']; ?
></td>
        </tr>
        <tr>
          <td colspan="2" ><br>
                         <? echo "".$r['msg_body'].""; ?>
                          <br>
                          <br /></td>
          </tr>

A link is presented here that takes you to the reply page:

        <tr>
          <td colspan="2" align="center"><br /><a
href="reply.php?mid=<?=$r['msg_id']; ?>&uid=<?=$user?>"
class="logout">Reply to this Message</a><br /></td>
          </tr>
                        <? } 
                        }?>
      </table> 

When looking at the message headers on the index page, you will see a link that points you to the view page; that link includes a mid variable. The script below uses that variable to retrieve the full message from the database:

<?php
            session_start();
            include "connect.php";
            $query_email = "SELECT email,user_id FROM user WHERE
user_id = ‘".$_SESSION['userid']."’";
            $result_email= mysql_query($query_email);
            $num_email= mysql_num_rows($result_email);
            if($num_email > 0 ){
            while($res = mysql_fetch_array($result_email)){
            $email = $res['email']; 
            $user = $res['user_id'];
}
            }else{
            echo mysql_error();
}          

The actual message is retrieved here and the result of the query is held in the $n variable. This variable is used to create a dynamic table later on:  

            $query = "select * from messages where msg_id =
‘".$_GET['mid']. "’";
            $re = mysql_query($query);
            if(!$re){
            echo mysql_error();
}
            $n = mysql_num_rows($re);
            $c= 1;

Once the message has been viewed, it will be classed as an old message, so we need to update the database to reflect this. The checked column in the messages table needs to be set to one, so that the next time you visit the index page it won’t retrieve this message as a new message:

//set checked flag to true
            $query_upd = "UPDATE messages SET checked = ‘1’ WHERE
msg_id = ‘".$_GET['mid']. "’"; 
            $res = mysql_query($query_upd);
?>

Conclusion

In this part we looked at the index page, which is at the heart of the application and from which you can view or delete individual messages. We also had a brief look at how to handle attachments in a message and how to integrate them into this application. The issue of attachments is avoided in most PHP email tutorials on the Internet, so I hope the code that I put together here will be helpful. The next article will look at the pages that are referenced by the navigation links.

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort