Sending MIME Email via Java

Now that we have seen how to use Perl the hard way, we should show you how to do it the easy way. In Chapter 16, Archiving and Cleaning a Mailbox, we will show how to use some of the mail-related Perl modules from the CPAN to create shorter and easier Perl scripts. In this section, we will show how to send a MIME message using the Java Mail API.

The short Java application that we will develop here will not mimic all of the functionality of the /bin/mail replacement shown previously, but it will show how a good API can make it possible to do hard tasks and can make simple tasks trivial. The purpose of this application is to send SMTP mail from Java, possibly with an optional MIME attachment. We will call our application MailOut.java, which will compile to MailOut.class.

In order to use the Java Mail API, as described in Chapter 14, The java Mail API, you will need access to its class files and those of the Java Activation Framework (JAF). After downloading and installing those files, your CLASSPATH environment variable is used to tell the Java runtime where they are. Under a bash shell it would look something like this:

$ CLASSPATH=.:/path/to/javamail-l.l/mail.jar:/path/to/jaf/activation.jar
$ export CLASSPATH

The Java Mail API gets the name of the local mailhost from a system property, mail.host. This is the outgoing SMTP server to use when sending mail. We could either set that property from within our code or rely on it to be set beforehand. If we set it ...

Get Programming Internet Email now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.