Commons Email is composed of a few classes that simplify sending email in a Java application. The overview
sections presented at the Jakarta site contain useful additional information.
The example in this section features a command-line tool written with the Commons Email that sends simple messages. I find it very handy for sending quick emails. You can extend this tool further to support HTML-formatted messages and attachments as well. The sample application requires JavaMail libraries and JavaBean Activation Framework libraries in the classpath. (The complete source can be found in the package in.co.narayanan.commons.email in the src folder of the source code.)
The design of the tool includes the following classes:
- CommandlineParser This class parses the arguments passed to the command line for creating an instance of the class SimpleMailCommand, which encapsulates the command arguments and the Commons Email class SimpleEmail. The SimpleMailCommand will be used later by the main class EmailBuddy to send the mail. Listing 12 presents the valid arguments needed to send a simple message.
Listing 12. CLI Syntax for Sending a Simple Email
java EmailBuddy -host mail.mysite.com
-to "firstname.lastname@example.org, email@example.com"
-subject "Commons Mail"
-message "Commons site is really good and interesting. You guys have to try it out"
Listing 13 illustrates Commons Email API usage.
Listing 13. Sample Commons Email Usage for Sending Simple Mail Message Taken from Jakarta Site
SimpleEmail email = new SimpleEmail();
email.addTo("firstname.lastname@example.org", "John Doe");
email.setMsg("This is a simple test of commons-email");
- SimpleMailCommand This class wraps the SimpleEmail class and creates the instance by parsing the command-line arguments.
- EmailBuddy This is the main class responsible for orchestrating the remaining classes.
From start to finish, the design would flow as follows:
- EmailBuddy delegates the command-line arguments to the CommandlineParser.
- CommandlineParser uses SimpleMailCommand to parse and populate the SimpleEmail Commons Email class.
- EmailBuddy fetches the SimpleEmail reference and calls a send method to dispatch the message.
In order to extend this tool--for example, to send a HTML-formatted message--you need to write a class HtmlMailCommand, which parses the command-line arguments and populates the HtmlEmail Commons Email class. Simply modify the CommandlineParser to use HtmlMailCommand.