JavaMail
JavaMail does exactly what you think; it allows you to send and receive email from within Java applications. It can be installed as an optional package if you are using Java 2 Standard Edition (J2SE), or it is already on your system if you have installed Java 2 Enterprise Edition (J2EE). Technically, the JavaMail API is just a set of abstract classes that represent an interface to a mail system, but Sun has bundled in a reference implementation that supports many of the popular email protocols such as IMAP, POP3, and SMTP, and JavaMail is royalty-free of course. In fact, in addition to the binaries, Sun is even making the source code available for the current version. I should also note that the reference implementation is completely written in Java and is, therefore, inherently platform independent. Support for email within applications has traditionally been a very platform-dependent issue.
Where Do I Get It?
Even if you are running J2EE, you are probably going to want to download the latest version (JavaMail 1.3) from here. Downloading the latest version will get you not only the mail.jar file, which contains all the .class files, but also all the Javadoc and demo code. After downloading the .zip file, unzip it and add mail.jar to the beginning of the Search/CLASSPATH for your favorite IDE. (If you already have a mail.jar in your Search/CLASSPATH, you should remove it or at least make sure the new one comes before it.) Then, download the JavaBeans Activation Framework 1.0.2 (JAF) from here, unzip it, and add activation.jar to your Search/CLASSPATH. Now, you should be ready to try your first JavaMail program.
Simple Example
Although you can send and receive email using JavaMail, most applications involve just sending email. So the program in Figure 1 does just that. Note that you will have to supply your own "to" and "from" email addresses as setting "host" to your local SMTP mail server.
|
Figure 1: Send email using JavaMail.
Let's walk through the example line by line.
import javax.mail.internet.MimeMessage;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
In the code shown above, you are importing all the classes from javax.mail that you are going to need. You could do this with import *'s, but I think giving the explicit path for examples helps you learn which classes are in each package.
{
public static void main(String[] argv)
{
String to = "
String from = "
String subject = "Test Message";
String myMessage = "Hello";
String host = "mail.yourwork.com";
This is where you need to do a little configuration. Set email addresses for "to" and "from" and assign "host" the hostname for your SMTP server.
props.put("mail.smtp.host", host);
Session session = Session.getDefaultInstance(props, null);
Here, you use a Properties object to associate a particular type of mail server host with the host and then configure a Session object with this Properties object. Many properties can be set using this method. See the Javadoc that came with your download of JavaMail for a complete listing.
try
{
msg.setRecipient(Message.RecipientType.TO,
(new InternetAddress(to)));
msg.setFrom(new InternetAddress(from));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(myMessage);
Transport.send(msg);
}
catch (MessagingException me)
{
me.printStackTrace();
}
Finally, you construct a Message object and set the to, from, subject, date, and message text. You then invoke the static method send() of the Transport class, and you're done. Something of particular interest is that setRecipient() method on Message takes two arguments. The first argument specifies whether the recipient is to be put in the "to" field, "cc" field, or "bcc" field. The second argument to setRecipient() can be either a single InternetAddress or an array of InternetAddresses.
HTML Example
Plain-text emails are great in some situations, but chances are you want to send email to customers, and Html emails are much more appealing than plain-text. The example in Figure 2 sends an HTML-formatted email message in which the string "Hello" is a large header over the "test message" text.
|
Figure 2: Send an HTML-formatted email message.
The Html version varies from the plain-text version in only a couple of places. There are a couple of new imports so that you can use a StringBuffer for appending together the Html without creating a lot of unnecessary strings. Also, there is a DataHandler for wrapping your string of HTML.
You can see from this example how you could dynamically load the StringBuffer with an HTML template from a file.You could then do some simple tag replacements in the HTML template to create customized HTML emails.
My Biggest Tip
In the HTML email example, you will see one other line that's different from the original plain-text version. Right after I created the session, I added the following line.
Turning debug on for the session can be critical when first developing with JavaMail. What it does is redirect to System.out all the messages coming back from the mail server, so in this case you see the server acknowledging the connection, verifying the senders and receivers, sending the message, and ending the session. So if you do make a mistake in development, setDebug(true) will help you find it.
Conclusion
Email enabling Java applications is easy and fun. You will probably need to download and install the latest versions of JavaMail and JAF packages from Sun, but once you have them installed and configured, sending plain-text or Html emails is pretty straightforward. In addition, the basic mechanism, when combined with markup tags, can be leveraged into a rich custom email generator. Finally, if you are having problems getting emails to send, you can turn on debug within a Session object so that you can trace where the problem is occurring.
Well, that wraps it up for this month. As always, feel free to
Michael J. Floyd is an Extreme Programmer and the Software Engineering Technical Lead for DivXNetworks. He is also a consultant for San Diego State University and can be reached at
LATEST COMMENTS
MC Press Online