Chapter 17. Java and Electronic Mail

Introduction

Sending and receiving email from a program is easy with Java. If you are writing an applet, you can simply get the browser to compose and send it for you. Otherwise, you can use the JavaMail Extension (package javax.mail) to both send and read mail. JavaMail provides three general categories of classes: Messages, Transports, and Stores. A Message, of course, represents one email message. A Transport is a way of sending a Message from your application into the network or Internet. A Store represents stored email messages and can be used to retrieve them as Message objects. Thus, a Transport is for sending email and a Store is for reading it. One other class, Session, is used to obtain references to the appropriate Store and/or Transport objects that you need to use.

The JavaMail package is included in JavaEE and can be downloaded for JavaSE use. It’s worth it: for the cost of a few minutes’ downloading time, you get the ability to send and receive electronic mail over a variety of network protocols. The JavaMail project is hosted on java.net. You can download a JAR file containing all the standard protocol providers (SMTP, IMAP, POP3), or an API JAR just to compile against, or download the basic API and download the protocols individually. There are Maven artifacts in [Maven Central as well. There is a JavaMail home page at Oracle. Finally, there is at least one alternative implementation, GNU JavaMail.

As you might have guessed from ...

Get Java Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.