0% found this document useful (0 votes)
44 views

Javamail Api: The Mail Is in

The document discusses sending emails using the JavaMail API. It provides an example Java program (JDMailer) that demonstrates how to: 1. Create a Session object and initialize it with mail server properties 2. Create a Message object and set the from, to, subject, and content fields 3. Send the message using the Transport.send() method The example creates a simple text email and sends it using the JavaMail API to demonstrate the basic steps for programmatically sending an email from a Java application.

Uploaded by

Rajesh Talreja
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Javamail Api: The Mail Is in

The document discusses sending emails using the JavaMail API. It provides an example Java program (JDMailer) that demonstrates how to: 1. Create a Session object and initialize it with mail server properties 2. Create a Message object and set the from, to, subject, and content fields 3. Send the message using the Transport.send() method The example creates a simple text email and sends it using the JavaMail API to demonstrate the basic steps for programmatically sending an email from a Java application.

Uploaded by

Rajesh Talreja
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

JavaMail API: The Mail is in

WRITER: Dr John Hunt


EMAIL: [email protected]
TELEPHONE: 01249 700491
FAX: 01249 700001

Introduction
There are many situations in which an application may need to send an email. For example, when
an error situation occurs, or when the next step in some workflow must be started, or in response to
some event that has occurred. Java applications are no exception to this and many Java stand alone
applications as well as two, three or n-tier applications may need to send email. In some cases these
applications will also need to support the retrieval of email (although this is probably less common
as many users will read email with one of the leading soultions such as Eudora, Outlook or similar).

Java provides access to email systems through the JavaMail API. The JavaMail API has been
developed over a number of years and currently version 1.3 of this JavaMail API is being readied
for release. It is possible to obtain the JavaMail API either as a separate downloadable jar from
Sun's website or as part of the Java 2 Enterprise Edition (also known as J2EE). You need to be
careful with the two appraches as the Enterprsie Edition Release 1.3.1 currently contains version 1.2
of the JavaMail API where as from the Sun web site it is possible to obtain both the 1.2 release
and the current verison of the 1.3 release.

In the remainder of this column we will look at create a basic email message, sending an email
message with an attachment and receiving an email message. This will cause us to examine the core
aspects of the JavaMail API and thus provide a sound basis for anyone wishing to get started with
this very useful set of packages.

The JavaMail API


The version of the JavaMail API used in this column is based on the 1.2 release provided as part of
the current J2EE release. The JavaMail API is made up of four packages. These are:

javax.mail This package provides the core classes for the generating, sending and reading email.
javax.mail.event Event Listeners and associated events for notifying application classes of mail
related acivities.
javax.mail.internet Classes specific to Internet mail systems including MIME type emails.
javax.mail.search Provides for searching through emails during the process of retrieving emails
form a server centric email system.

As you will see form the above table, all the packages start javax and thus the JavaMail API is a
standard language extension (and thus an optional package).

It is important to realise that the JavaMail API focusses on eMail user Agent type programs such as
Eudora and not on implementing an email server. Thus the API provides for reading, constructing
and sending electronic messages via a server that understands en email protocol such as SMTP or
POP. SMTP stands for Simple Mail Transfer Protocol (SMTP) which is the protocol most often
used to send email. POP stands for Post Office Protocol (currently in version 3 and often referred to
as POP3) which is the protocol most oftne used to receive email.
Like a number of other APIs in Java (most notabley JDBC) JavaMail is not tied to one particular
protocol or one particular type of email server. Instead JavaMail relies on the appropriate protocol
implementation known as protocol specific providers. Sun provides a set of protocol specific
providers with JavaMail, these include SMTP, POP and IMAP. If you have used older versions of
the JavaMail API (for example 1.1.3) then you will probably be pleased to see that a POP provider
is now supplied with JavaMail (previously it was necessary to download form Sun a separate JAR
that would add a POP provider to your JavaMail installation).

Setting up JavaMail
If you are going to use the JavaMail API directly form the J2EE 1.3.1 release than you do not need
to do anything special to get things to work (other than making sure that the j2ee.jar file is on your
classpath). If you intend to use the JavaMail independtly of the J2EE installation then you will need
to follow the instlation instructions provided with the version of the JavMail API you obtain.

Sending email
We will start off by sending a very simple email to a single user. The email will contain only text.
This is the simplest example, but in many cases is also exactly what is required. For example, if a
server application needs to send an email to a support engineer informing them of some problem
then it is likley that the email message will be textualand include the error message. Thus although
this is a simple example it is both very useful and one on whcih we will build in the rest of the
column.

We shall be using classes in the javax.mail package and in some cases inthis column the
javax.mail.internet package.

The steps that we must follow to create an email and send it are:

1) create an initialise a session object


2) create and put text into a message object
3) send the message using the static Transport.send() method.

The session object represents a basic email session. That is it represents a single communication
channel with an email server. It is through this session object that everything else operates.

The session object needs to know some details in order to connect to the appropriate meail server.
This information is passed to the session object via a Proeprties object. A properties object is part of
the java.util package (and not part of the javax.mail package or subpackages). It is used in many
situations and provides a dictionary like look-up facilities. That is given a key it will return a string
value. Thus it is possibel to place configuration information into a Properties obejct that canbe
picked up by the session object. Once such example is the "mail.smtp.host" proeprty. This can be
defined within a Property object by defining "mail.smtp.host" as a key and setting the value to be
"thor" if "thor" is the name of the smtp host. Of course you replace "thor" with the name, usually a
full URL, of your target email server.
Figure 1: The basics of sending email with JavaMail

Figure 1 presents a very simple email program (called JDMailer). This Java application takes three
parameters, the email address of the receipient of the message, the subject heading of the email and
a string for the contents of the email message.

Notice that the code imports the java.util.Properties class and two of the JavaMail packages, namely
javax.mail.* and javax.mail.internet.*. We need to import these two packages as the Session,
Message, Address and Transport classes are defined in the javax.mail package. In turn the
MimeMessager and InternetAddress classes are defined in the javax.mail.internet package.

The first thing that the JDMailer class does is to create a Properties object and store the
mail.smtp.host property in it. Note that yous should replace this with the address of whatever mail
server you are using.

Next we create an instance of the Session object. This can be done in a number of ways but here we
are creating the session object using the "factory" method getDefaultInstance. This method takes
two parameters the proeprties indicating which mail server to use and an authenticator object if one
is being used. At the moment we are not using an authenticator so we will pass in null here.
Following this we set the session debug flag to be true so that some output will be generated by the
JavaMail classes to indicate what ishappening behind the scenes.
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);

Now we come to the first point where the program has been protocol specific. We need to create a
message object suitable for the mail system in use and in this case it is a MimeMessage object:

Message msg = new MimeMessage(session);

We now have a message object that will represent our email message. However we need to set up a
number of attributes for the message such as who sent the message and where it should go. This is
done sby creating an instance of the InternetAddress class (from the javax.mail.internet package).
And then using the constructed object as the paremter for either the setFrom or setRecipient
methods. As well as the set versions of these methods there are also add versions.
Also note that the setRecipient method takes two parameters. The first parameter is the recipient
type (such as to, CC, BCC) etc. and is defined by the Message inner class Message.RecipientType.
The JDMailer example uses the TO type, but there are also Message.RecipientType.CC
Message.RecipientType.BCC. The snippet of code the illustrates this form the
JDMailer exmaple is presented below:

InternetAddress addressFrom = new InternetAddress("[email protected]");


msg.setFrom(addressFrom);
Address addressTo=new InternetAddress(args[0]);
msg.setRecipient(Message.RecipientType.TO, addressTo);

Note that as far as SMTP is concerned the "from" field is optional. We coudl there have left this out
and this example woudl still have worked. In fact when we send an email in this way we can make
up a from email address (such as Bilbo.Baggins") and the email will still be sent! We can now set
up the subject header for the message and the content of the email message. In our example we take
them from the command line.

msg.setSubject(args[1]);
msg.setContent(args[2], "text/plain");

Note that for the content of the message it is necessary to set the content type. In this case we are
using "text/plain" to indicate that the content type is plain text. We could have used the setText
method on the message which woudl have set the text and the content type in one step. This is fine
if all you ever want to do is to send text. However we coudl change the content type to be
"text/html" if we wished to send HTML by email using setContent.

We now have an email message which is ready to be sent to the receipient. This is done using the
Transport class. There are two ways in whcih we could use this class. For example we could us the
static method Transport.send(). In our example we obtain the Transport object formt he session and
then use the instance method send on the Transport object obtained.

Finally note that the whole main method throws an Exception. This is because numerous steps in
the creation and sending of an email message may throw exceptions. To keep this example simple
we are merely passing the exception out of the main method. In most cases you will need to handle
the exceptions locally in a try catch block.
Figure 2: A .bat file set up to add the j2ee.jar to the class path for compilation

Figure 2 illustrates a simple compile.bat file used to compile this code and figure 3 a simple run.bat
file that illustrates how the JDMailer is exected. Note that it is necessary to add the j2ee.jar to the
class path.

Figure 3: A .bat file for running the JDMailr example with appropriate parameters

You should now be able to send an email message. The end result as displayed in Eudora is
presented in figure 4.

Figure 4: An email message sent by JDMailer read by Eudora

Now that you have looked at an exmaple of a program that can send a message to a single email
address it is straight forward to extend this principle to multiple email addresses. The
JDManyMailer does just this. It takes a list of email addresses and sends a message with the
provided subject and content to each. This is done by creating an array of InternetAddress objects
and using the msg.setRecipients(Message.RecipientType.TO, addrs) method (note that extra "s").
Note that in the JDManyMailer example the receiptant addresses are provided at the end of the
commend line options.
Figure 5: Modifying the JDMailer class to send an email message to multiple recipients

Receiving messages
So far in this column we have focussed on sending emails. The other aspect of an email tool is
receiving emails. We will now look at what support the JavaMail API provides for reading emails
from an email server. As the most common way in which email is read is from a POP3 server we
will focus on this example. Figure 6 illustrates a simple program that will read email from a POP3
server called JDMailReader.
Figure 6 A Java application that reads email from a POP3 email server

Just as with sending emails the starting point is the Session object. However note that this time we
do not need to define any specific properties. Instead our properties object is left empty.

Properties props = new Properties();


Session session = Session.getDefaultInstance(props, null);

When reading email we have to get hold of a store object. The store object obtained must be
appropriate for the specified protocol. For example, as we are using POP3 we must specify the
“pop3” protocol. A Store is an object that models a message store and its access protocol, for
storing and retrieving messages. Once the store object has been obtained it is necessary to connect
the stroe to the email server that will supply the email messages./ This is done using the connect
method of the Store object. This comment takes the name of the server (e.g. Thor), a user name and
a user password. This is used to authenticate the user to the email server and identify the email
messgages for this user. An alternative to providing the user name and password direvtly is to use
an Authenticator object. An Authenticator object is one which will supply the username and
password on demand (for exmaple by promoting the user for these items of information). The two
statements that obtain and connect the store are presented below:

Store store = session.getStore("pop3");


store.connect("thor", args[0], args[1]);
We are now in a position to be able to obtain an Folder object that will supply the actual email
messages. A POP3 server only has one folder, the “INBOX” folder. This folder holds the emails
held on the email server that have not been down loaded yet. Note that an IMAP server could have
additional folders that can be managed and searched by the JavaMail API.

Folder folder = store.getFolder("INBOX");

At this point we have something that can be used to read the contents of the “INBOX” but has yet
to do so. To actually download the messages it is necessary to open the folder. This can be done in a
number of ways. For example, it is possible to indicate that the folder should be opened in read only
mode so that messages are not actually removed form the server (useful for testing your
applications). The class Folder defines serveral constants that allow you to control how the Folder is
opened. For example Folder.READ_WRITE and Folder.READ_ONLY. We will use the read only
option here:

folder.open(Folder.READ_ONLY);

Now we have the messages in the folder object we can start to make use of them. You can retrieve
the messages using the method getMessages() on the folder object. This returns an array of Message
objects that you can now loop through:

Message messages[] = folder.getMessages();


for (int i=0; i<messages.length; i++) {
messages[i].writeTo(System.out);
System.out.println("--------------------");
}

Note that the messages are actually only retrieved form the server when you access them, thus if
you only access the first message and exit the others will not be retrieved.

Finally you have to close the folder and store:

folder.close(false);
store.close();

To reply to a message is very straight forward. The message class contains a reply method that can
be used to generate a reply message object. This message object can then be set uyp as appropriate,
for example:

Message reply = message.reply(false0;


reply.setFrom(new InternetAddress(“[email protected]”);
reply.setText(“Thanks”);
Transport.send(reply);

The only question that really remains is how do you delete an email? The answer is that you have
first open the folder in read/write mode:

folder.open(Folder.READ_WRITE);

After this you can set the flag for each email you retrieve to "deleted":

msg.setFlag(Flags.Flag.DELETED,true);
The email isn't actually deleted until you close the folder with "true" as the parameter:

folder.close(true);

Notice that this is the only flag that the POP3 server takes any notice of.

Summary
In this column we have looked at the JavaMail API. This API allows a Java program to create and
send emails, to read emails and to reply to them. In additon to what has been presented here it is
also possible to send attachments and to deal with mulkti-part MIME messages.

Online References
Sun's JavaMail home page http://java.sun.com/products/javamail/
Sun's JavaMail Tutorial http://developer.java.sun.com/developer/onlineTraining/JavaMail/
jGuru JavaMail FAQ page http://www.jguru.com/faq/JavaMail

Facts at a glance
? JavaMail provides a protocol independent interface to email servers
? A session object represents the users current interaction with the email server
? Transport class is used to send emails
? Stores and folders support reading emails
? JavaMail includes supports SMTP, POP3 and IMAP protocols.

You might also like