12
Tue, Nov
6 New Articles

JavaMail

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

If you were to ask the average person if there is anything to the Internet besides the Web and email, I’m sure you’d get “no” for an answer. Most programmers know that Java’s strength, besides the platform-independence thing, lies in its networking capabilities. Knowing that, as well as knowing that email is such a huge part of everyday life, it’s not a reach to assume Java has email capabilities. Java does have these capabilities in JavaMail. This article tells you how to use JavaMail to send an email message and how to give Web applications a professional touch.

We all get annoying email, like those messages from users who don’t know how the Caps Lock button works or spam mail. Of course, email was never meant to be annoying; the early pioneers who built the Internet intended it as a communication tool. One of those pioneers was Ray Tomlinson of the company Bolt, Beranek and Newman, which is now known as BBN Technologies and part of GTE.

In 1971, right about the time Reggie Jackson hit his historic 520-foot home run off a Tiger Stadium light tower during the All-Star game in Detroit, Tomlinson invented what we now know as email and sent the very first email message: “Testing 1-2-3.” He gave us the first functional email program about a year later, in 1972, when Jackson was about to become the first major-league baseball player with facial hair since 1914. But you already knew all that. Fast-forward 29 years: The novelty of email has been replaced by its status as an everyday part of life. Not only do we use email clients all the time, but now, with JavaMail, we can incorporate email into our Web applications as well.

You’ve Got Mail

JavaMail Version 1.1.3 comes as an extension to the standard Java Development Kit (JDK), meaning that it is not included in any JDK download and must be downloaded separately. JavaMail works with the JavaBeans Activation Framework (JAF), which is also an extension of the JDK. This article presents a sample application that receives email via POP3. This means I need POP3 support, for which I’ll use Sun’s free POP3 Provider. (Links to download these packages are listed in the References and Related Materials section of this article.)


The downloads of these products include various demos and documentation, but what you’ll need is three JAR files: activation.jar, mail.jar, and pop3.jar. First, I’ll clarify the ingredients of this article’s example. The mail.jar file is JavaMail. JavaMail requires the assistance of JAF, the activation.jar file, to handle the data content of the many different types of files that can be sent across the Internet. The activation.jar file handles many low- level tasks required by JavaMail, and chances are you’ll never use the classes in this archive unless you want to add attachments when sending email.

To receive mail, there are two main protocols in use today: POP3 and Internet Mail Access Protocol (IMAP). IMAP support is included in JavaMail and is superior to POP3 in virtually every way. The trouble is that POP3 is still much more widely used than IMAP. This is why, to have POP3 support when using JavaMail, you must download the POP3 Provider, which is pure Java but not included in the Java family in any way, not even as an extension. Also, JavaMail is built with client-side email in mind, and, as such, it cannot be used to build a mail server.

Attachment: Sample Code

I’ll outline some key classes in JavaMail by showing you an example of a servlet that reads and sends regular text email and throws in a JavaServer Page (JSP) that acts as an error page, displaying exceptions and then sending a message to notify the appropriate personnel about the error.

The example servlet begins with a simple HTML form where a user enters values for his Simple Mail Transport Protocol (SMTP) and POP3 servers, user name, and password. The user name and password values are used for the POP3 server. Typically, SMTP servers don’t require a login. The main servlet receives the parameters posted by the HTML form and (as shown in Figure 1) creates a list of email messages that are available to read.

Now I’ll pick apart the code that gets you to this point. You first need to establish SMTP and POP3 services in the servlet before you can do anything. The SMTP host is used by JavaMail in a simple yet specific manner. When JavaMail needs to know the SMTP host name, it looks to the system Properties object for a property called smtp.mail.host; you must input the property and the property’s value. Setting up POP3 is a little more involved, but it’s an easy three-step process:
1. Get a Session object.
2. Get a Store object.
3. Connect to the Store.

Email Sessions

A Session in the vernacular of JavaMail is not to be confused with an HttpSession of the servlet API. A JavaMail Session doesn’t maintain the status, or state, of a connection as an HttpSession does. A Session object holds various user configuration properties, like the user’s email address and host names. Once you have the Session object, you can get the Store object by calling the Session’s getStore() method.

The code snippets in Figure 2 detail the process of setting up SMTP and POP3 support. As you can see in Figure 2, you supply the getStore() method with a String parameter, identifying what type of service you’ll need; in this case, it’s POP3. Finally, when you get the Store object, you can connect to the resource, using the host name, user name, and password supplied in the HTML form.

In the unabridged version of the code shown in Figure 2, I put the Store object to the HttpSession object so that I can use it after I’ve logged on. If I didn’t do this, I’d need some way of recreating the Store object so that I could retrieve new messages during my HttpSession. Now that you’re connected to a POP3 server, it’s time to get the mail. Now you’ll see the differences between POP3 and IMAP and how JavaMail makes life easy no matter what provider you use.


To get your mail, you need to instantiate a Folder object, which tells JavaMail where our messages are located on the mail server.

Folders are a natural concept for IMAP, but POP3 has no such thing. Fortunately, the JavaMail specification requires that POP3 providers implement a virtual folder called INBOX. This way, when you create the Store, using the method described earlier, you only need to change the string from POP3 to IMAP (or whatever mail-retrieving protocol comes down the pike).

After you create the folder, you can open it using—you guessed it—its open() method. The open() method takes an int as its parameter, which tells JavaMail what mode the folder will be in, or how you want to open the folder. Since this is an example of getting email through your browser, you’ll open the folder in read-only mode so that the messages stay on the server. Figure 2, section B, details the steps needed to retrieve email messages.

Receive All

After you’ve gone through all the steps to set up POP3 and SMTP services and you’ve opened a folder on the host, you’re ready to get the messages. Evoking the getMessages() method of the folder will give you an array of Message objects that you can use to create the message list. If you’ve ever used your favorite email client to view email source code, you know there’s a lot more to an email message than just the body of the message. JavaMail gives you several methods in the Message class to get at that information, and the example uses a few of those methods to create the message list; namely, the ones that extract the date, sender, and subject of the message.

An important feature of JavaMail is that the Message class is “lightweight.” In layman’s terms, that means you don’t get parts of the message you haven’t asked for. So if your good buddy was gracious enough to send you an MPEG file of the entire movie Caddyshack, you wouldn’t have to wait a week for it to download if your email client used JavaMail.

As shown in Figure 3, viewing an individual message from the list is one of the more involved portions of the servlet, which could get even more complicated quite easily. The details are in the read() method, where the Message you want to view is cast to, or changed into, a MimeMessage. Check the MimeMessage to see if it’s HTML mail; if so, just have the servlet send the message out through its OutputStream. If it’s regular text, the method formats the text a little, then sends it out to the browser; if it’s another type of MimeMessage called a MimeMultipart, that usually means there are attachments, and the example simply prints out what kind of attachments they are (i.e., their MIME types and their names).

Now that you have the lowdown on the key classes of retrieving and reading email, I’ll get into what it takes to send email. Sending email is a little easier, except, as I mentioned before, if you want to send attachments. I’ll leave it up to you to figure that one out.

Because the example doesn’t send attachments, you get to use MimeMessage instead of MimeMultipart as the type of message to send. Once an instance of MimeMessage is available to use, you can employ some simple methods to construct the scary-looking email source I mentioned before. The example uses some of the methods of the MimeMessage object to set the sender, recipient, subject, and body of the message. These parameters are retrieved from an HTML form that the servlet itself puts out to a browser. After you’ve built the MimeMessage, you use one of the few methods of the Transport class called send() to—you guessed it again—send the message. The method takes the MimeMessage you created earlier as its parameter.

That’s it for sending email. All the code for sending messages is shown in Figure 2, section C.


Send All

One of the features I put into the servlet is a JSP error page. Of course, there are only a million things that could go wrong when sending an email across the Internet. If something does go wrong, the error will be captured and displayed along with some words that are meaningful to an actual user, and the cryptic text of the error will be sent as an email to somebody who can decipher its meaning (presumably to an IT person). Without going into lengthy detail about how JSP error pages work, I’ll point you to Figure 2, section D, which shows the 3 lines of code you’ll need to send exceptions to a JSP error page.

Once the JSP has control of the application and has the Exception object, simply get the text of the Exception object, as shown in Figure 2, section E, and send it, using the same procedures I discussed for sending email. Figure 4 shows what happens when I try to log on to my POP3 server using an invalid password. The error page displays a brief message and explains that a message was sent to somebody who could do something about it. Figure 5 shows the message sent by the JSP error page. To spice up the page a little, you could add several other items of interest to the email, like query string parameters, cookie text, or headers.

More Email Ideas

You’ve seen how using JavaMail in your Web applications is not difficult. In addition to being easy to use, it’ll give your Web applications a nice touch.

There are several different applications of JavaMail. You could set up some email accounts to receive messages of a different variety on your mail server. Using, for example, a servlet that reads a calendar file and sends an email to everyone in your company, reminding them of the cutoff date for month-end or inventory processing. A servlet could check inventory files and send email to appropriate personnel when levels reach a certain strike level, either high or low. Brainstorm a while, and you’ll find there are many ways to employ JavaMail in your company.

REFERENCES AND RELATED MATERIALS

• BBN Technologies Web site: www.gte.com/AboutGTE/gto/bbnt/index.html
• JavaBeans Activation Framework Web site: http://java.sun.com/beans/glasgow/jaf.html
• JavaMail API Web site (to download JavaMail and POP3 Provider): www.java.sun.com/products/javamail/index.html

Form_Follows_Function-_HTML_Form_Validation...04-00.png 397x273

Figure 1: This list of email messages is displayed upon logging in to a POP3 server.


Code snippets from ServletMail.java

A) Setting up SMTP and POP3 services

Properties p = System.getProperties();

p.put(“mail.smtp.host”, smtpSvr);

mailSession = Session.getInstance(p, null);

store = mailSession.getStore(“pop3”);

store.connect(pop3Svr, usr, pwd);

B) Retrieving messages

inbox = store.getFolder(“INBOX”);

inbox.open(Folder.READ_ONLY);

messages = inbox.getMessages();

C) Sending messages

MimeMessage message = new MimeMessage(mailSession);

message.setFrom(new InternetAddress(from));

message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));

message.setSubject(subject);

message.setText(text);

Transport.send(message);

D) Sending an exception from a servlet to a JSP

try

{

. . .

}

catch(Exception e)

{

request.setAttribute(“javax.servlet.jsp.jspException”, e);

RequestDispatcher rd = getServletContext().getRequestDispatcher(“/error.jsp”);

rd.forward(request, response);

}

E) Getting an Exception ready to send as text

StringBuffer buffer = new StringBuffer();

StringWriter writer = new StringWriter();

error.printStackTrace(new PrintWriter(writer));

buffer.append(writer.getBuffer());

Figure 2: These are code snippets from both ServletMail.java and error.jsp.

Form_Follows_Function-_HTML_Form_Validation...05-00.png 397x279

Figure 3: This message is displayed upon selecting a message from the list of emails.


Form_Follows_Function-_HTML_Form_Validation...06-00.png 397x279

Figure 4: This is the output of error.jsp after successfully sending an email about an error in ServletMail.

Form_Follows_Function-_HTML_Form_Validation...06-01.png 406x293

Figure 5: This detailed error message is sent by error.jsp.


Don Denoncourt

Don Denoncourt is a freelance consultant. He can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Don Denoncourt available now on the MC Press Bookstore.

Java Application Strategies for iSeries and AS/400 Java Application Strategies for iSeries and AS/400
Explore the realities of using Java to develop real-world OS/400 applications.
List Price $89.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: