HOME  |    TRAINING  |   FREE TUTORIALS   |   JOBS
Find out more about our new RSS feed.
FREE Tutorial
PROFESSIONAL WAP PART 5 - E-MAIL AND E-COMMERCE

CATEGORY
SEARCH OUR OTHER TUTORIALS

DESCRIPTION

One of the most important lessons for an Internet retailer is to ensure that the online buying experience is as easy and as enjoyable for the customer as possible. It is essential that the customer feels in control of the situation and is informed and reassured every step of way.


This free tutorial is a sample from the book Professional WAP.


A customer who cannot easily retrace his or her steps, change or cancel their order, or is confused or uncertain as to what is happening before, during and after a transaction, is unlikely to return, or to recommend the site to their friends and colleagues.

A frequent feature of on-line ordering is an acknowledgement e-mail sent to the customer to reassure them that the order has been successfully placed, and is being dealt with; this technique is used to good effect on such sites as Amazon, with its instant order acknowledgement.

We will now look at an example of such a situation, and the code needed to ensure that a customer receives an e-mail thanking them for their order, and confirming both the goods ordered and the price ordered at, within minutes (if not seconds) of placing their order.

E-Mail for E-Commerce Order Confirmation

This example uses a Java servlet to send an automatic e-mail, acknowledging an order placed from a WAP device. But first we will take a look at the WML deck from which the order is made.

OrderConfirmation.wml

The card resulting from the code below is displayed just prior to an order being placed on our imaginary system. The customer is asked to enter his or her e-mail address and can then click to place the order:

   
<?xml version="1.0"?> 
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">

<wml>
  <card id="OrderConfirmation" title="Place Order">
   <p>
   E-mail:<input name="email" maxlength="100" />
   <br/>
   Place Order!
     <go href=" http://localhost/servlet/WAPOrderConfirmationEmail"
      method="post">
      <postfield name="email" value="$email"/>
     </go>
   </anchor>
   </p>
  </card>
 </wml>

Using the emulator supplied by Phone.com, the WML page above is displayed in quite a primitive way. Input of information is via the phone's keypad, and the input box and "Place Order!" link are displayed on separate screens:


We first type in the e-mail address to which the acknowledgement is to be sent. Pressing the OK button enables us to then proceed to the next screen, where we can confirm the order by selecting the Place Order! option:


WAPOrderConfirmation.java

The Java servlet, WAPOrderConfirmation, which is invoked by the WML page above, takes the user's e-mail address and sends a simple response. In the real world Wireless Transaction Layer Security (WTLS) would be used to secure this order - especially if details such as credit card numbers were being transmitted - however, for the purposes of the example, we will ignore security requirements here.

Let's plunge straight into the code; the relevant lines will be explained afterwards.

   
import java.io.IOException;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.wrox.util.WML;

public class WAPOrderConfirmation extends HttpServlet {

  public void doPost (HttpServletRequest request,
             HttpServletResponse response)
   throws ServletException, IOException {

  String host = "smtp.yourISP.net";
  String from = "orders@machincorp.co.uk";
  String to = request.getParameter("email");
  String subject = "Your order with Machin Corp International";
  StringBuffer text = new StringBuffer();

  text.append("Thank you for ordering from 
               MachinCorp International");
  text.append("\n\n");
  text.append("If you need to get in touch with us about your order ");
  text.append("please send an e-mail message to
               orders@machincorp.co.uk ");
  text.append("(or just reply to this message)");
  text.append("\n\n");
  text.append("Please note that you can view the 
               status of your account and ");
  text.append("orders, cancel undispatched orders, and change the ");
  text.append("delivery or invoice information for
              undispatched orders at ");
  text.append("any time through the \"My Account\" 
              link in the side ");
  text.append("panel of our Web site.");
  text.append("\n\n");
  text.append("MachinCorp.co.uk Customer Service");
  text.append("\n\n");
  text.append("orders@machincorp.co.uk \t 
              http://www.machincorp.co.uk");
  try {
   //Get system properties
   Properties props = System.getProperties();

   //Setup mail server
   props.put("mail.smtp.host", host);

   //Get session
   Session session = Session.getInstance(props, null);
   session.setDebug(false);

   //Define message
   MimeMessage message = new MimeMessage(session);
   message.setFrom(new InternetAddress(from));
   message.addRecipient(Message.RecipientType.TO, 
               new InternetAddress(to));
   message.setSubject(subject);
   message.setText(text.toString());

   //send message
   Transport.send(message);

   WML wml = new WML();
   wml.addCard("OrderSent", "Order Sent");
   wml.println("<p align=\"center\">" +
     "Thank you for your order! " +
     "</p>");
   wml.endCard();
   wml.outputWML(response, false);

  }catch (Exception e) {
   e.printStackTrace();
  }
} 
}

The first part of the above code is simply involved in setting up all the text for the e-mail to be sent. The important JavaMail section of this code occupies less than a dozen lines of code. Considering what this code is actually doing, this is really quite remarkable!

Essentially there are three steps to the process of composing and sending an email using JavaMail:

1. Create a valid mail session
2. Create a message object
3. Send the message object

java.lang.Properties are used throughout the JavaMail API to provide a mechanism to control the behavior of many methods:

   
//Get system properties
Properties props = System.getProperties();

//Setup mail server
props.put("mail.smtp.host", host);

The first step in sending an e-mail is to instantiate a Session object.

   ]
//Get session
session session = Session.getInstance(props, null);
session.setDebug(false);

At the core of sending mail is the creation of a MIME message object:

   
//Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, 
             new InternetAddress(to));
message.setSubject(subject);
message.setText(text.toString());

We may then use the send() method of the Transport class, passing in this message object. This brevity in the send() is possible because we have specified the SMTP host in the session using the Properties object as shown above:

   
//send message
Transport.send(message);

Once the order confirmation e-mail is sent to the specified address, a quick WML response is sent back to the device. The final part of the code simply uses the WML class we saw earlier to generate the WML, which is shown here:

A Complete E-Mail Application

In the example given above, we have seen how to use JavaMail to send e-mail messages. We will now outline the other core operations of a mail system:

  • Viewing lists of mail messages
  • Reading specific messages
  • Dealing with the capabilities of the device, and MIME types
  • Deleting mail from a mail folder

Once we have discussed how to incorporate this essential functionality of e-mail within WAP applications, we can move on to our second WAP example, WAPMail, which will incorporate all of these features into a primitive, but functional e-mail system.

POP3 Programming Hints

Unlike the more advanced IMAP4 protocol, POP3 only supports a single queue of messages, and
does not cater for multiple folders. In JavaMail, this message queue is represented by a single folder named "INBOX".

In a similar manner to the way we have created SMTP sessions, we must also open up a session to the POP3 service in order to be able to retrieve our email:

   
//Get POP3 Session
Session pop3Session = Session.getInstance
             (System.getProperties(), null);
pop3Session.setDebug(false);

Once the session is created, you must connect to the POP3 message store using your username (uid) and password (pwd) to access your e-mail messages:

   
String pop3host = "pop.yourISP.net";
String username = request.getParameter("uid"); 
             //e.g. user@wapbook.org.uk
String password = request.getParameter("pwd");

//Get POP3 Store
Store pop3Store = pop3Session.getStore("pop3"); pop3Store.connect(pop3host, username, password);

Viewing the INBOX

To view the INBOX - the only folder for POP3 stores - the folder must be retrieved and then opened, specifying an access permission. In the WAPMail example later in the chapter, we will see that READ_ONLY is used for viewing the INBOX and reading mail, whereas READ_WRITE is needed to remove e-mail from the inbox.

   
//Get Folder
Folder folder = pop3Store.getFolder(inboxString);
folder.open(Folder.READ_ONLY);

//Get Messages
Message message[] = folder.getMessages();

//Show messages list
. . . 

Folder objects should be closed when you have finished performing operations on them to free
up resources:

  
//Close connection
folder.close(false);

Determining the Number of Mail Messages

To determine the number of e-mails waiting to be read in the inbox, you can use the getMessageCount() method of the javax.mail.folder object:

   
//Get number of e-mails waiting in folder
int totalCount = folder.getMessageCount();

Reading a Mail Message

To read a particular message the getMesssage(int Index) method of the folder object can
be used.

   
//Get a specific Message
int messageIndex = Integer.parseInt(request.getParameter("index"));
Message message = folder.getMessage(messageIndex);

//Show the message
. . . 

How the Java Activation Framework (JAF) is used

To correctly display a MIME e-mail we must first decide what the content of the mail is. If the mail is plain text - it has a MIME type of "text/plain" - then we can display it quite simply. If, however, the MIME type is more complex - for example, the mail is an image or an acrobat file - then we cannot display it directly on a first generation WAP phone, such as the Nokia 7110.

   
// Determine Message contents data type
Object messageContent = message.getContent();

if (message.isMimeType("text/plain") && 
            messageContent instanceof String) {
  // Show message
} else {
  //Error! WAP Mail can only read plaintext e-mails
}

Deleting a message from a POP3 folder

POP3 does not support the folder.expunge() method that can be used with IMAP. To delete, and expunge, messages, you must set the Flags.Flag.DELETED flag on the messages to true by closing the folder using the folder.close(true) method:

   
//Get Folder
Folder folder = pop3Store.getFolder(inboxString);
folder.open(Folder.READ_WRITE);

//Get Directory
int messageIndex = Integer.parseInt
             (request.getParameter("index"));
Message message = folder.getMessage(messageIndex);
message.setFlag(Flags.Flag.DELETED, true);

//close connection
folder.close(true);




5 RELATED COURSES AVAILABLE
MICROSOFT INTERNET EXPLORER 6.0 INTERNET INTRODUCTION
This course provides readers with an introduction to the concept of the Internet and the opportunity to gain a br....
MICROSOFT INTERNET EXPLORER 5.0 INTERNET INTRODUCTION
This course is a self-paced introduction to browsing the internet and sending e-mail using MS Internet Explorer a....
I-NET+ MODULE 7 - THE WORLD WIDE WEB SERVICE
On completion of this module, readers will be able to: understand how the World Wide Web service works, understan....
HTML 4.0 INTRODUCTION
To create, format and publish a small website using HTML 4.0. You will learn to create web pages incorporating fo....
JAVASCRIPT PROGRAMMING
This training course aims to teach the reader the fundamentals of JavaScript. This course covers topics such as -....
 
0 RELATED JOBS AVAILABLE
CONTACT US
Wednesday 3rd December 2008  © COPYRIGHT 2008 - VISUALSOFT