Some reader favorites:
EJB fundamentals and session beans
Create a scrollable virtual desktop in Swing
Web services test code generator
Klaus Berg has recently released a test-code generator for JUnit-based Web service clients. If you're developing Web services
using Axis2 and XMLBeans this wizard could turn your JUnit test client coding into a powerful code generation process. It
also has uses for those using GUI-based testing tools like soapUI.
| Memory Analysis in Eclipse |
| Enterprise AJAX - Transcend the Hype |
Page 2 of 5
Once you have a session, create a message. In this example, you're setting the message's from and to email addresses, the subject, and the body text, all taken originally from the command line. You're also setting some header information, including the date, and you can specify cc recipients if you want.
Finally, you send the message via the javax.mail.Transport class. If you wonder how it knows about our mail session, look back at the message's constructor.
The setText(...) convenience method in class javax.mail.Message (inherited from the javax.mail.Part interface) sets the message content to the supplied string and sets the MIME type to text/plain.
You're not limited to plain text, though: you can send other content types via the setDataHandler(...) method. In most cases you can take "other content types" to mean file attachments, such as Word documents, but for something
a bit more interesting, check out this code for sending a Java serialized object:
ByteArrayOutputStream byteStream=new ByteArrayOutputStream(); ObjectOutputStream objectStream=new ObjectOutputStream(byteStream); objectStream.writeObject(theObject); msg.setDataHandler(new DataHandler( new ByteArrayDataSource( byteStream.toByteArray(), "lotontech/javaobject" )));
You won't find the DataHandler class within the javax.mail.* package structure because it belongs to the JavaBeans Activation Framework (JAF) package javax.activation. Remember, you downloaded the JAF distribution as well as JavaMail. JAF provides a mechanism for handling typed data content, which for Internet content means MIME types.
And if you really do try the code above for sending a Java object by email, you'll have trouble locating the ByteArrayDataSource class, as neither mail.jar nor activation.jar include it. Try looking in the JavaMail demo directory!
As for those file attachments that you're more likely to be interested in initially, you would create a javax.activation.FileDataSource instance in the DataHandler's constructor. Of course, you're not likely to send a file alone; rather, it will probably be an attachment to a text message.
For that you need to understand the concept of multipart messages, so I'll introduce that concept now, in the context of receiving
email.
Earlier, I introduced the javax.mail.Part interface implemented by javax.mail.Message. I'll now explain its message parts, which are important in this example. To start, take a look at Figure 3.
Figure 3 shows a Message as created in the previous example that is both a message and message part, because it implements the Part interface. For any part, you can get its content (any Java object), and, in the case of a simple text message, the content
object may be a String. For a multipart message, the content will be of type Multipart, from which we can get hold of the individual body parts, which themselves implement the Part interface.

Figure 3. UML diagram for the mail.Part interface
In practice, all will become apparent as you step through the code for a SimpleReceiver class, which I'll present in three sections: first, the class definition and the main(...) method that takes connection details from the command line; second, the receive(...) method that captures and steps through the incoming messages; and finally, the printMessage(...) method that prints the header information and content of each message.
Here's the first section:
package com.lotontech.mail;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
/**
* A simple email receiver class.
*/
public class SimpleReceiver
{
/**
* Main method to receive messages from the mail server specified
* as command line arguments.
*/
public static void main(String args[])
{
try
{
String popServer=args[0];
String popUser=args[1];
String popPassword=args[2];
receive(popServer, popUser, popPassword);
}
catch (Exception ex)
{
System.out.println("Usage: java com.lotontech.mail.SimpleReceiver"
+" popServer popUser popPassword");
}
System.exit(0);
}
I'll take you through a proper test drive later, but for now here is the command line to run it (remember to replace the command arguments with your mail settings):
> java com.lotontech.mail.SimpleReceiver pop.myIsp.net myUserName myPassword
The receive(...) method -- called from main(...) -- opens your POP3 INBOX and steps through the messages in turn, each time calling printMessage(...). Here is the code:
/**
* "receive" method to fetch messages and process them.
*/
public static void receive(String popServer, String popUser
, String popPassword)
{
Store store=null;
Folder folder=null;
try
{
// -- Get hold of the default session --
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
// -- Get hold of a POP3 message store, and connect to it --
store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);
// -- Try to get hold of the default folder --
folder = store.getDefaultFolder();
if (folder == null) throw new Exception("No default folder");
// -- ...and its INBOX --
folder = folder.getFolder("INBOX");
if (folder == null) throw new Exception("No POP3 INBOX");
// -- Open the folder for read only --
folder.open(Folder.READ_ONLY);
// -- Get the message wrappers and process them --
Message[] msgs = folder.getMessages();
for (int msgNum = 0; msgNum < msgs.length; msgNum++)
{
printMessage(msgs[msgNum]);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
// -- Close down nicely --
try
{
if (folder!=null) folder.close(false);
if (store!=null) store.close();
}
catch (Exception ex2) {ex2.printStackTrace();}
}
}
Notice that you're obtaining a POP3 message-store wrapper from the session, then connecting to it using the mail settings originally supplied on the command line.
Once connected, you get a handle on the default folder -- effectively the root of the folder tree -- and, from there, the INBOX folder that holds the inbound messages. You open the INBOX for read-only access; you get hold of the messages and step through them one by one.