If you want to do full e-mail from another language such as RPG or COBOL, you normally have to buy an e-mail solution....
By submitting your personal information, you agree that TechTarget and its partners may contact you regarding relevant content, products and special offers.
You can, however, add e-mail support to your applications and business processes easily with Java -- and with very little coding.
Have you ever thought of automatically sending an order acknowledgement as an Excel workbook to a customer via e-mail? It's not hard to do with Java -- even if you call it from an RPG program on your iSeries. You can also receive e-mail automatically with Java from a mail server. A Java application can "read" the e-mail and its attachments. If they are formatted data (such as an Excel workbook), you can automatically edit and then post the updated data to your database.
With Java's mail support you can use a Java program (application) to automatically send e-mail (text or HTML) with attachments, receive e-mail with attachments, reply to e-mail, forward e-mail and delete e-mail from your mail folders.
I've found that I can automate processes and workflows between companies easily using e-mail. Why? Unlike Web services, messaging and other technologies, all companies already have the ability to send and receive e-mail outside their organization. As a result, setting up an automated workflow application that uses e-mail for input and output on my end won't require my customers, partners, etc. to involve their IT staff in building or configuring interfaces to us -- a huge benefit when trying to easily implement integrated, distributed applications.
The Java Mail API
The Java Mail API offers a simple, consistent way to write mail applications regardless of the mail service provider (mail server) used and the operating environment -- iSeries, Windows, Linux or Web application server). It even accommodates many of the differences on how mail servers are set up with security constraints. Whether you use an in-house mail server or an outside mail server provided by your ISP, you should be able to use the Java Mail API to send and receive mail easily. The Java Mail API implements a lot of the mail functions defined in the World Wide Web mail standards (known as RFCs).
Mail service providers
The three most common sources of mail servers to interface with are your company's in-house mail server (if one is available), a large, public mail server service (Yahoo or Google), or your ISP's mail server.
There are different types of mail providers that can be used to send or receive mail. The mail server you use determines the type of mail providers you'll need to use in your application. In the example in this article, I used the default mail providers included with the Java Mail API jar files -- Simple Mail Transport Protocol (SMTP) for sending mail and Post Office Protocol 3 (POP3) for receiving mail from an Inbox mail folder. You can add any provider you need through the Provider interface if you want to create your own mail server service. Here are the mail providers in the mail.jar file:
# JavaMail IMAP provider Sun Microsystems, Inc protocol=imap; type=store; class=com.sun.mail.imap.IMAPStore; vendor=Sun Microsystems, Inc; # JavaMail SMTP provider Sun Microsystems, Inc protocol=smtp; type=transport; class=com.sun.mail.smtp.SMTPTransport; vendor=Sun Microsystems, Inc;
Here's the POP3 provider included in the pop3.jar file from Sun:
protocol=pop3; type=store; class=com.sun.mail.pop3.POP3Store; vendor=Sun Microsy stems, Inc;
Key Java Mail classes
The Java Mail API has a few key classes you'll use to send and receive mail. I've summarized them in the below table.
|Java Mail Class
|Session||This is the first class you use. It creates an instance of a session with support for mail services: send, receive and so on. It has many properties and default values used in a mail session. Transports and Stores are created for a specific session.|
|MimeMessage||This is used to create a simple mail message to send or receive. You will set and get different message properties such as from, recipient, subject and text.|
|InternetAddress||An InternetAddress includes a user e-mail address (firstname.lastname@example.org) and a name (Jim Mason). You provide InternetAddress objects as elements of messages for form, recipient, etc.|
|Transport||This is a class that represents a mail transport. It provides application support for naming, connection and listening to connection events. It is also used to send messages.|
|Authenticator||Some mail servers, such as Yahoo, require a mail user to authenticate himself to the server. If authentication is needed, you create a subclass of Authenticator to implement a getPasswordAuthentication method that returns a PasswordAuthentication object with a user name and password. In our example, I created MailAuthenticator as the subclass. When the server checks authentication, the getPasswordAuthentication method is called by the Java Mail framework.|
|Store||A Store object represents a mail store you connect to, such as a POP3 mailbox. Once connected to a store, you can access folders such as "Inbox" to receive your mail.|
|Folder||A folder holds mail in a mail store. If you are using POP3 protocol, the only folder you'll access is "Inbox". If your server supports another protocol, such as IMAP4, you can access other named folders for mail as well.|
|MimeMultipart||A MimeMultipart object is returned when you access the MimeMessage with the getContent method. This object can contain multiple MimeBodyPart objects.|
|MimeBodyPart||A MimeBodyPart object lets you access content objects and headers from a mail message using an input stream. There's also a setText method to set the content easily. Each body part has a MIME type that determines what the content access methods should be. The default MIME type is "text/plain".|
|POP3Message||This is a subclass of MimeMessage specific to a POP3 service. The example included here pulls the text content of the e-mail message from the entire multipart message returned. The package for this class is com.sun.mail.pop3|
Java Mail Environment properties
The Java Mail API services use different environment properties to configure their behavior, primarily for the different mail protocols supported by the service.
|Property name||Usage||Default value|
|mail.store.protocol||Specifies the default message access protocol. Session.getStore() returns a store supporting this protocol. You can also explicitly specify the protocol you want to use for a session.||First protocol found in the config files (javamail.properties)|
|mail.transport.protocol/td>||Session.getTransport() returns the protocol.||First protocol found in the config files (javamail.properties)|
|mail.host||Store and Transport connect methods use this value to find the default mail host.||The local machine|
|mail.user||Specifies the mail user when connecting to a mail server if not explicitly set on the connect method. Generally, you'll want to explicitly set this on the connect.||user.name|
|mail.protocol.host||Sets the protocol-specific mail server overriding the mail.host setting. We set this as a Java System value for SMTP mail to connect to the Yahoo SMTP mail server as follows:
|mail.protocol.user||Sets the protocol-specific mail user to use on connections overriding the mail.user||Mail.user|
|mail.from||Return address to use by default||username@host|
|mail.protocol.auth||This defines whether the server requires an authentication object to connect. In our example, we set this with a system value as follows:
Writing a Java mail client
I used Eclipse 3.0 to create my simple Java mail client to send and receive mail. Eclipse is free from www.eclipse.org. You can also you use any other Java toolset. Most iSeries developers use IBM's WebSphere Development Studio Client for the iSeries. You should use at least JDK 1.4.2 or higher for a mail application, although older ones can work.
With Eclipse, I created a Java project first. Then to set up my environment for a mail application, I added the three Java Mail API files to my Java project's build path and I created a MailClient1.java class in the src folder of my project. The build path has the imports section for the javax.mail classes and the POP3Message class I imported.
import javax.mail.*; import javax.mail.internet.*; import com.sun.mail.pop3.POP3Message;
Sending mail from Java
I chose to use Yahoo's mail servers to send and receive mail. Each mail server uses specific mail protocols to send and receive that are implemented a specific way. You need to get this information from your mail provider. Yahoo has a specific URL to send mail (smtp.mail.yahoo.com) and a specific URL to receive mail (pop.mail.yahoo.com). For Yahoo, the server also requires an authentication object to specify the correct user and password for the connection.
Another issue you may run into is an ISP that doesn't allow you to send mail using a program or client on the default SMTP port of 25. One of the ISPs I use has this restriction. To get around the problem, Yahoo also runs its mail servers on port 587. To set the port for the SMTP mail server, I had to set another system property (environment variable) the Java Mail SMTP protocol accesses, "mail.smtp.port". Here's the setting for the SMTP port for the mail client: Usually you'll have to supply valid authentication information (user id and password) in a PasswordAuthentication object to send or receive mail to the mail server. Your mail provider can give you this information if you don't already have it.
// if isp blocks port 25 for smtp, use another port (yahoo=587) System.setProperty("mail.smtp.port", "587");
To send mail, I created a method that does the following:
- Loaded our mail user configuration from a properties file
- Created a properties object with the SMTP server URL and authentication value
- Retrieved a mail session using the properties and the authentication object
- Created a new MimeMessage and set message properties
- Retrieved a transport instance from the session for SMTP
- Connected the transport to the server
- Sent the message using the transport
Here's a test mail message I sent to myself from Java over the Yahoo mail server.
Receiving mail in Java
I chose to use Yahoo's mail servers to receive mail also. For Yahoo, the server also requires an authentication object to specify the correct user and password for the connection.
To receive mail, I created a method that did the following:
- Loaded our mail user configuration from a properties file
- Created a properties object with the SMTP server URL and authentication value
- Retrieved a session using the properties and the authentication object
- From the session, we retrieved a mail store object for a POP3 mail server
- Connected to the mail store
- Opened the "INBOX" folder in read-only mode
- Listed the first 10 messages to the system console
- Displayed the detail of the first message on the system console
This shows the resulting mail message output received from the mail server that I dumped to the system console in Java:
// results from getmail // a partial listing of mail in the inbox Sat May 07 12:11:26 EDT 2005 from: "Mason, Gabrielle"
RE: apartment stuff Fri May 06 15:01:25 EDT 2005 from: Jim Mason eBLVD Online Meeting Invitation from Jim Mason Fri May 06 15:01:06 EDT 2005 from: Nikki WOW Entry - What can you use it for? // details of a single mail item read in Java Mail item .. date: null from: "Mason, Gabrielle" subject: RE: apartment stuff text: This is a multi-part message in MIME format. ------_=_NextPart_001_01C5531F.6BCDA0F1 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Hey Dad, =20 I don't know if Mom told you any updates about the apartment. Gabrielle Mason
To read a mail message, I turned the input stream from the MimeBodyPart of the MimeMessage into a text string for display. The actual output from this method included ALL parts of the mail message as text including headers. I abbreviated the output shown to focus just on the text content of the mail message.
Content type determines how you'll read and send e-mails. In my case, I received mail in plain/text format as the content type (vs. plain/HTML format). You CAN use the HTML format to send nicely formatted e-mails with style sheets. You know those annoying vendor e-mails you get with the nice graphics? That's how they do it.
After receiving all the mail, I shut down the mail folder I opened and closed the mail store.
Java Mail development options
You can add the mail support to your application by downloading the three mail API jar files from Sun's Web site directly (mail.jar, activation.jar and pop3.jar) or you can just use the latest version of the J2EE jar file (j2ee.jar) that includes the mail support.
Once you've downloaded the mail jar flies, you'll need to add them to your classpath. The line below shows how I added the jar files to the classpath in the Windows Command Shell environment:
Remember to also run the System.setProperty methods to set the SMTP environment variables for mail server ("mail.smtp.host") and the authentication value ("mail.stmp.auth") if needed.
We've covered only the basics of sending and receiving mail in this article. There is a lot more you can do with Java Mail. If you can take the time, investigate the resources listed below.
- For Java Runtime Environments or Development Kits, visit http://java.sun.com/.
- For the Java Mail API jar files, visit http://java.sun.com/developer/onlineTraining/JavaMail/exercises/MailSetup/.
- For another tutorial on Java Mail (jGuru: Fundamentals of the JavaMail API), visit http://java.sun.com/developer/onlineTraining/JavaMail/.
- The JavaMail API Design spec included with the Java Mail API jar files: JavaMail-1.1.pdf.
- At www.ebt-now.com, we develop custom Java applications for mail and other applications.
- Join the free user group www.quickwebsupport.com for more iSeries Java and WebSphere development information.
About the author: Jim Mason works at ebt-now, an iSeries Web integration company, providing QuickWebServices for iSeries customers: Web planning, WebSphere, WebFacing, Web development, Web networking, Web support, Web security and training services. Jim is creating a self-study course for RPG programmers that teaches "hands-on" rapid visual development with WDSC for all types of iSeries and e-business applications without the need to become a Java expert. Rochester Initiative will publish the course. You can reach Jim at email@example.com.