22
Fri, Nov
1 New Articles

Java Journal: You've Got JavaMail

Java
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times
First, a big thanks to everybody who took the time to drop me an email after last month's first Java Journal column. I selected this month's topic, as I will every month's topic, based on your feedback. I received lots of great suggestions, many of which you will see in the coming months.

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.

  import javax.mail.internet.InternetAddress;
  import javax.mail.internet.MimeMessage;
  import javax.mail.Message;
  import javax.mail.MessagingException;
  import javax.mail.Session;
  import javax.mail.Transport;

  public class JavaMailDemo
  {
    public static void main(String[] argv)    
    {
      String to = "This email address is being protected from spambots. You need JavaScript enabled to view it.";
      String from = "This email address is being protected from spambots. You need JavaScript enabled to view it.";
      String subject = "Test Message";
      String myMessage = "Hello";
      String host = "mail.yourwork.com"; 

      Properties props = new Properties();
      props.put("mail.smtp.host", host);
      Session session = Session.getDefaultInstance(props, null);

      Message msg = new MimeMessage(session);
      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();
      }
    }
  }

Figure 1: Send email using JavaMail.

Let's walk through the example line by line.

  import javax.mail.internet.InternetAddress;
  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 class JavaMailDemo
  {
    public static void main(String[] argv)    
    {
      String to = "This email address is being protected from spambots. You need JavaScript enabled to view it.";
      String from = "This email address is being protected from spambots. You need JavaScript enabled to view it.";
      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.

      Properties props = new Properties();
      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.

      Message msg = new MimeMessage(session);
      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.

  import java.util.Date;
  import java.util.Properties;
  import javax.activation.DataHandler;
  import javax.mail.internet.InternetAddress;
  import javax.mail.internet.MimeMessage;
  import javax.mail.Message;
  import javax.mail.MessagingException;
  import javax.mail.Session;
  import javax.mail.Transport;

  public class JavaMailHTMLDemo
  {
    public static void main(String[] argv)
    {
      String to = "This email address is being protected from spambots. You need JavaScript enabled to view it.";
      String from = "This email address is being protected from spambots. You need JavaScript enabled to view it.";
      String subject = "Test Message";
      String myMessage = "Hello";
      String host = "mail.yourwork.com"; 

      Properties props = new Properties();
      props.put("mail.smtp.host", host);
      Session session = Session.getDefaultInstance(props, null);
      session.setDebug(true);
      Message msg = new MimeMessage(session);
      try
      {
        msg.setRecipient(Message.RecipientType.TO, 
                        (new InternetAddress(to)));
        msg.setFrom(new InternetAddress(from));
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        StringBuffer sb = new StringBuffer();
        sb.append(" ");
        sb.append(" ");
        sb.append(" ");</font></tt><br><tt><font face="Courier New">        sb.append(" ");
        sb.append(" ");
        sb.append(" ");
        sb.append("

Hello

");

        sb.append("test message ");
        sb.append(" ");
        sb.append(" ");

        msg.setDataHandler(new DataHandler(sb.toString(),
                           "text/html"));

        Transport.send(msg);
        }
        catch (MessagingException me)
        {
          me.printStackTrace();
        }
    }
}

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.

      session.setDebug(true);


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 This email address is being protected from spambots. You need JavaScript enabled to view it. with your suggestions for topics that you would like to see covered in the Java Journal.

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 This email address is being protected from spambots. You need JavaScript enabled to view it..

Michael Floyd

Michael J. Floyd is the Vice President of Engineering for DivX, Inc.

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: