Enterprise J2ME Developing Mobile Java Applications [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Enterprise J2ME Developing Mobile Java Applications [Electronic resources] - نسخه متنی

Michael Juntao Yuan

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید



8.2 Introducing Mail4ME


Mail4ME is an Open Source library that provides lightweight email APIs for all J2ME profiles. Since Mail4ME is released under the CPL (Common Public License), you are free to integrate it into your proprietary software solutions. However, I do encourage you to release your changes and enhancements back to the community. This way, your additional features can be supported in future versions of Mail4ME. This book covers the v1.0 release of Mail4ME.

For devices that support TCP/IP socket connections, Mail4ME applications connect to Internet mail servers directly. But raw socket is not mandatory in MIDP specifications. For devices or networks that support only the mandatory HTTP, Mail4ME provides a special mode that utilizes an HTTP proxy. The source code of the proxy servlet and config instructions are included in the Mail4ME download package. As we will see, the use of the HTTP proxy is largely transparent to Mail4ME client developers.

In the next two sections, I introduce a sample application, MailSample, that demonstrates how to use Mail4ME APIs. MIDlet Suite MailSample contains two MIDlets: SendDemo demonstrates how to send out email via an SMTP server; InboxDemo demonstrates how to read and manipulate email from a POP3/IMAP server. Figure 8.2 shows the application in action. Make sure that you replace the dummy server addresses and authentication information in the MailSample.jad file before you try it out.


Figure 8.2. Demo: Access email from J2ME/MIDP devices.



8.2.1 Send Email


To send a text message via Mail4ME is very easy. You first need to compose a message and encapsulate it in a Message object. Listing 8.1 illustrates how to assemble a text message. All arguments passed to the Message constructor are in the String format.


Email Attachments and MIME Types


As we know, an email message can take text or binary content as attachments. Those contents are encoded into plain text format according to rules defined in the Multipurpose Internet Messaging Extensions (MIME) specification. MIME is a standard type system defined by IETF. For example, a plain text message part has MIME type plain/text; an HTML part has MIME type text/html; a PNG image part has MIME type image/png; a JAR file has MIME type application/java-archive. The encoded parts and their MIME information are appended to the message body during transmission. The recipient decodes and displays each part according to its MIME type. Mail4ME provides limited support for MIME decoding.

Listing 8.1. Assemble an outgoing message



Message message = new Message(my_address, recipient_address, subject);
message.addBodyLine( body );

Then, you connect the SMTP server and send the message via the SmtpClient object (Listing 8.2). The code comment illustrates the use of HTTP proxy. The message is successfully sent if the code does not throw an exception.

Listing 8.2. Send a message using SmtpClient


SmtpClient smtpClient = null;
// use proxy:
// smtpClient = new SmtpClient(
// new de.trantor.mail.http.ConnectionImpl(
// httpHost, 8080), hostname);
smtpClient = new SmtpClient(hostname);
smtpClient.open(smtpHost, 0, false, smtpUser, smtpPass);
smtpClient.sendMessage(message);
smtpClient.close();


8.2.2 Receive and Manipulate Messages


Now, let's see how we receive email via Mail4ME. First, we open a connection to the mail server via the InboxClient object. Listing 8.3 demonstrates how to connect to POP3/IMAP servers with or without the HTTP proxy.

Listing 8.3. Connect to a POP3 server



InboxClient inbox;
if (imap) {
// If you use a proxy
// inbox = new ImapClient(
// new de.trantor.mail.http.ConnectionImpl(
// httpHost, 8080));
inbox = new ImapClient();
} else {
// If you use a proxy
// inbox = new Pop3Client(
// new de.trantor.mail.http.ConnectionImpl(
// httpHost, 8080));
inbox = new Pop3Client();
}
inbox.open(pop3Host, 0, false, pop3User, pop3Pass);

Now, we can get a list of new messages and their summaries. Method getMessageList() in Listing 8.4 returns an MIDP List object that displays a list of new emails. Each email's sender address and subject line is displayed as a List item. Vector msgNumbers keeps track of the index of each message in the list. This is necessary, since if you delete messages from the list, the list index goes out of sync with the message index on the POP3/IMAP server.

Listing 8.4. Retrieve messages from the POP3 server



private List getMessageList() throws MailException, IOException {
List result = new List("Inbox", Choice.IMPLICIT);
int count = inbox.getMessageCount();
for (int i = 0; i < count; i++) {
String uid = inbox.getUniqueId(i);
int size = inbox.getSize(i);
Message message = inbox.getHeaders(i);
result.append(
message.getHeaderValue("Subject", "No subject") + " ("
+ Message.getMachineAddress(
message.getHeaderValue("From", "No sender"))
+ ")", null);
// msgNumbers.insertElementAt(new Integer(i), 0);
msgNumbers.addElement(new Integer(i));
}
return result;
}

Listing 8.5 deletes the selected message from the server, the message list, and the msgNumbers vector.

Listing 8.5. Delete messages from the POP3 server



int num = msgList.getSelectedIndex();
inbox.removeMessage(((Integer)msgNumbers.elementAt(num)).intValue());
msgList.delete(msgList.getSelectedIndex());
msgNumbers.removeElementAt(num);


8.2.3 Display Message Parts


What if we want to display the details of a message? Listing 8.6 illustrates how to display the selected message in an MIDP Form.

Listing 8.6. Display a message



int num = msgList.getSelectedIndex();
if (num == -1) return;
Message message = inbox.getMessage(
((Integer)msgNumbers.elementAt(num)).intValue());
Form readScreen = new Form("Message details");
readScreen.append(
new StringItem("From:",
Message.getMachineAddress(
message.getHeaderValue("From",
"No sender"))));
readScreen.append(
new StringItem("Date:",
message.getHeaderValue("Date", "No date")));
readScreen.append(
new StringItem("Subject:",
message.getHeaderValue("Subject",
"No subject")));
MimeDecoder mime = new MimeDecoder(message);
addPartToScreen(mime, readScreen);

The method addPartToScreen() actually displays the content of the message based on the MIME types of its parts. For more information on MIME attachments, see the sidebar "Email Attachments and MIME Types." Mail4ME supports the decoding of two MIME types: the text/plain type and image/png type. A simple text message contains only a text/plain part. Method addPartToScreen() goes through message parts recursively, as shown in Listing 8.7.

Listing 8.7. Display a multi-body message



private void addPartToScreen(MimeDecoder mime, Form screen) {
if (mime.getPartCount() == 0) {
if ("image/png".equals(mime.getType())) {
byte[] bytes = mime.getBodyBytes();
screen.append(Image.createImage(bytes, 0, bytes.length));
} else if ((mime.getType() == null) ||
("text/plain".equals(mime.getType()))) {
String s = ";
for (int i = 0; i < mime.getBodyLineCount(); i++) {
s = s + "\n" + mime.getBodyLine(i);
}
screen.append(s);
} else {
screen.append("\n[Unable to display \" +
mime.getType() + "\" part.]");
}
} else {
for (int p = 0; p < mime.getPartCount(); p++) {
addPartToScreen(mime.getPart(p), screen);
}
}
}

Now, we have seen the entire process of sending, receiving, displaying, and deleting email messages using the Mail4ME package. In recap, Figure 8.3 shows the classes in the Mail4ME package and illustrates their relationships.


Figure 8.3. Mail4ME class diagram.


In the rest of this chapter, we go beyond simple email and look at PIM APIs for J2ME.


/ 204