Software

Include both HTML and plain text in one e-mail

Don't know whether to send your e-mail as HTML or simple text to a particular user? Find out how to send both with this Java tip.


By Henri Yandell

The ability to promote products directly to a targeted consumer is a marketing department's dream. And e-mail marketing has helped make this type of focused promotion much easier. If you send your messages as HTML mail, you can boost their impact by including pictures and polished formatting. However, not all recipients want to read HTML; some prefer text.

One solution might be to ask your customers what type of e-mail they prefer. But there is another, more efficient solution: Include both formats in one e-mail. To do this, you need the javax.mail package that's part of J2EE and available at java.sun.com.

As you can see in Listing A, sending a simple text e-mail message with Java is pretty easy. Notice, the javax mail package is imported.

To send multiple formats in one e-mail, you have to use Parts. An e-mail has a Content, which can be a simple String or a Multipart. A Multipart is made up of many BodyParts. A BodyPart may contain a String or a Multipart. For this example, we're sending e-mails that contain Multipart, with two BodyParts—plaintext and HTML.

Note that there are different types of Multipart. The two most common are multipart/mixed and multipart/alternative. One shows both on the same page, while the other selects the best format for the user. Listing B shows an example of multipart/alternative. For more information on Multiparts, check the online javadoc for javax.mail.

 

Getting more out of your Java app
What are some ways you get more functionality out of your Java applications? Share your tips and suggestions by sending us an e-mail with your ideas, or post a comment below.

 

Editor's Picks