Java Reference
In-Depth Information
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:
Message
s,
Transport
s, and
Store
s. 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 appro-
priate
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 re-
ceive electronic mail over a variety of network protocols. The JavaMail project is hosted on
(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 imple-
mentation, GNU JavaMail.
As you might have guessed from
Chapter 13
, it's also not that big a stretch to write code
yourself that contacts an SMTP server and pretends to be a mail program. Hey, why pretend?
You really have a mail program at that point! This is not shown in the topic, but is available
in the
javasrc
repo under
src/main/java/email/SmtpTalk.java
, for use as an aid to understand-
ing the SMTP protocol.