Send J2ME Mail

Hi, most of you may have wondered how to send mail using J2Me. With the support of J2ME and J2SE, it becomes simple. If you have developed Standalone/Desktop mail sending applications before, this may be even easier. If not please reffer to the following article before
http://ruchiram4.blogspot.com/2008/12/sending-mail-using-java.html

I assume that you are familiar with J2ME basics (Sun Wireless Toolkit, Midlets) and have the basic knowledge in deploying an application in Tomcat Server.

The architecture for sending J2ME is slightly restricted. You cannot have your own SMTP Server. So, the J2ME application works by first establishing a connecting with a website/service and passing the relevant values(Eg: Message Subject, To Address, Message Text) to it.
In my case, I used Tomcat and created a Servlet to handle such requests.

So, we have two applications running seperately.

1. The J2ME Mobile application
2. The J2SE Server Application

On receiving the request, the Servlet would process and make the connections with the SMTP server and push the mail to the SMTP Server. In my example I have used the very simple scenario and removed all the complexities regarding code. The user does not get any chance to alter the E-Mail options. The E-Mail addresses are hardcoded. However, the E-Mail Subject and Text are sent from the application(Even though the user doesn't get any opportunity to type the message or subject. This has been done to reduce the complexities in understanding the code)

First, we must write a Servlet (which can handle HTTP requests) and make it such that it can send a mail.
We use the HTTP POST method in sending the E-Mail from the Mobile Application to the Servlet. So, we need to Override "doPost" method of the Servlet(Since our Servlet extends HttpServlet).


Our Server Application reads two values from the Mobile Application(Even though the end user does not get an opportunity to alter these values, they have been hardcoded in the J2ME application). So first, we must retrieve them.

They can be received by the following way;



BufferedReader rdr = request.getReader();

String subject= rdr.readLine();
String text= rdr.readLine();

rdr.close();



We can get a BufferedReader object using the request object passed to the Servlet. (A HttpServletRequest object is passed to the Servlet by its Container. You do not need to worry about this. It is done by Tomcat)
We read line by line which was sent by the Mobile Application. Then we close the Reader.

Now, we call the private void testMail(String subject, String text) method which I have written. This is responsible for sending the mail.




Properties prop= new Properties();
prop.setProperty("mail.smtp.host", "localhost");
Session session = Session.getDefaultInstance(prop);

InternetAddress from = new InternetAddress("");
InternetAddress to = new InternetAddress("");

MimeMessage msg= new MimeMessage(session);
msg.setFrom(from);
msg.addRecipient(RecipientType.TO, to);

msg.setSubject(subject);
msg.setText(text);

Transport.send(msg);



Now, build this application and deploy it in Tomcat Sever. Also remember to add the Servlet mapping and URL pattern to the web.xml file located inside Tomcat.

Start Tomcat. Now, you should have your Web Application running. Next, start the SMTP server. WindowsXP, by default has a SMTP server inbuilt. But you may need to install it as an option when installing windows. It appears under the IIS facility. Or there are some other open source SMTP servers such as Apache James Server.

The next part deals with developing the J2ME application which is intended to run on a mobile device. Since, it is difficult to test an application on a real device without having the hardware, Sun has developed a device simulator which can be downloaded from

http://java.sun.com/products/sjwtoolkit/download.html

We will create a Midlet to start our J2ME application. We will create a method for establishing the connection and sending the mail parameters to the Servlet.



public void sendPOST_Message() throws IOException{

String url="http://localhost:8080/MailApplication/MailServlet";

HttpConnection conn= (HttpConnection) Connector.open(url);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "text/plain");

OutputStream out= conn.openOutputStream();
PrintStream pout = new PrintStream(out);

pout.println("Subject");
pout.println("My Message");

pout.close();
out.close();

}



This method is the method responsible for sending the mail parameters to the Servlet.

HttpConnection conn= (HttpConnection) Connector.open(url);

We first, instantiate a HttpConnection type object by calling the static open method of Connector object.

conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "text/plain");

We set the method of the http connection by Setting it to Post. The next is a compulsary line needed to send a Post request to the Server. You must tell the type of what you send via the request.

OutputStream out= conn.openOutputStream();
PrintStream pout = new PrintStream(out);

We instantiate an OutputStream object by calling the openOutputStream() method of the HttpConnection type object. We can create a PrintStream object by passing this OutputStream into it.



pout.println("Hello World");
pout.println("Sample Message");

pout.close();
out.close();



Next, we print the values which needs to be sent from the J2ME application to the Servlet. We have hardcoded these values. In real, there should be Textboxes to get the input from the user and then send these parameters into the the Servlet by this method. But for simplicity, we will only demonstrate this case.

Make sure to call the close methods of these stream objects, as it may not work otherwise.



public void commandAction(Command cmd, Displayable arg1) {

if(cmd==cmdSend){

Thread t = new Thread(new Runnable() {

public void run() {
try {

sendPOST_Message();
} catch (IOException ex) {
ex.printStackTrace();
}

}
});
t.start();
}
}



Next, we call our sendPOST_Message() method as the event when a button click occurs in our J2ME application.

In the commandAction (Command,Displayable)

method, we do three things.

1. Check which button called the event commandAction (Command,Displayable) to trigger. (This method is invoked in a button click event. If we have multiple buttons, we need to find out what button was clicked. But, in our application, since we have only one button, the if() clause would not make a difference)

2. Create a Thread

3. Call the sendPOST_Message() method, from inside the thread and start the thread

NOTE: We MUST use Threads when trying to do time consuming operations as Network connecting operations. Otherwise, it may get into a deadlock and not proceed.

Here is the complete code for the J2ME mail application. It includes just one button to send the mail.




/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package net.ruch.j2me.mail;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
* @author Ruchira
*/

public class MailMidlet extends MIDlet implements CommandListener{

Form form;
Command cmdSend;

public MailMidlet() {

form= new Form("Main Form");
cmdSend= new Command("Send mail", Command.OK, 0);
}

public void startApp() {

form.addCommand(cmdSend);
Display.getDisplay(this).setCurrent(form);
form.setCommandListener(this);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}


public void sendPOST_Message() throws IOException{

String url="http://localhost:8080/MailApplication/MailServlet";
HttpConnection conn= (HttpConnection) Connector.open(url);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "text/plain");

OutputStream out= conn.openOutputStream();
PrintStream pout = new PrintStream(out);

pout.println("HelloWorld");
pout.println("This is a sample message ");

pout.close();
out.close();

}

public void commandAction(Command cmd, Displayable arg1) {

if(cmd==cmdSend){

Thread t = new Thread(new Runnable() {

public void run() {
try {

sendPOST_Message();
} catch (IOException ex) {
ex.printStackTrace();
}

}
});
t.start();
}
}

}



So, now, compile and run the application. Hopefully, you should get the mail.

I referred to the following site in building the application. This site displays a complete code segment for a mobile J2ME E-Mail application. I just filtered out the most necessary steps required to make it easier to understand. For a complete application please reffer to this.

http://www.java-tips.org/java-me-tips/midp/sending-email-from-j2me-devices.html

Comments

Popular posts from this blog

Encrypt and Decrypt Images Using Java

Build your own Network sniffer

ASP Response.Write newline