Java Mail API: Accessing Email

In the previous sections, we have discussed how to send mails. Let us now discuss how to retrieve email messages from a mail server such as Gmail. There exists two primary protocols that describe syntax and semantics to retrieve emails: Post Office Protocol (POP) and Internet Message Access Protocol (IMAP) [Figure 15.8:].

Figure 15.8: Sending and retrieving mails

1. POP

POP is an acronym for Post Office Protocol. Its current version is 3.0 and is known as POP3. It is a standard protocol (see RFC 1939 for details) that supports basic functions (download and delete) for electronic mail. Like most Internet protocols, the POP3 is a simple request-response protocol.

A POP3 server listens for connections on standard TCP port 110. Once a connection is established, the communication between the client and server takes places in the form of commands and responses. The commands are sent by clients while server sends responses.

An example POP3 session is shown below:

S: <wait for connection on TCP port 110>

C: <open connection>// e.g. telnet localhost 110

S:  +OK uroy POP3 server (JAMES POP3 Server 2.3.2) ready

C:  user abc

S:  +OK

C:  pass abc

S:  +OK    Welcome abc

C:  STAT

S:  +OK 2 320

C:  LIST

S:  +OK 2 messages (320 octets)

S:  1 120

S:  2 200

S:  .

C:  RETR 1

S:  +OK 120 octets

S:  <the POP3 server sends message 1>

S:  .

C:  DELE 1

S:  +OK    message 1 deleted

C:  RETR 2

S:  +OK 200 octets

S:  <the POP3 server sends message 2>

S:  .

C:  DELE 2

S:  +OK    message 2 deleted

C:  QUIT

S:  +OK    Apache James POP3 Server signing off.

C:  <close connection>

S:  <wait for next connection>

The telnet application may be used to establish a connection to the pop server. Once the connection has been established, the client application must send username and password information to the email server. If the login credentials are accepted, the user can access the mailbox to download or delete messages.

2. IMAP

The POP provides the basic mail access functions and has become popular for its simplicity. However, it lacks many important features that are increasingly in demand today.

To provide finer control over manageability of mails, a new one Internet Message Access Protocol (IMAP) was introduced. It provides more functionalities and flexibility to the e-mail clients. The current version of IMAP is 4 and is known as IMAP4. Using IMAP4, clients can manipulate messages stored on a remote server in the same way they manipulate messages stored in the local machine. IMAP has some specific advantages over its competitor POP, some of which are mentioned below:

  • In POP, clients get disconnected after downloading messages. However, IMAP4 allows clients stay connected and download messages any time during the session.
  • Unlike POP, which allows only one client to be connected to the mailbox at a time, the IMAP allows multiple clients to access a mailbox simultaneously. It also provides facilities to the clients to detect changes made to the mailbox by other connected clients.
  • The IMAP4 allows us to retrieve individual parts of the message. This means a client can retrieve the text portion of a message without retrieving attached files.
  • In IMAP, clients can detect the message states (such as read, replied, deleted) using flags, which are stored on the server. POP does not specify any such mechanism.
  • It is possible to create, rename, and/or delete mailboxes (usually represented as folders) with IMAP4. It enables us in copying and moving messages across mailboxes. It also enables us to create shared and public
  • IMAP4 clients can ask the server to provide messages that meet a search criteria. So, clients need not download all messages to perform this searching.

Although, IMAP overcomes many of the pitfalls of POP, it introduces additional complexity which, in turn, introduces server-side workaround. For example, a malicious client can provide critical search criteria to the server to search messages that can potentially consume significant amount of server resources. Due to tremendous complexity of IMAP fewer e-mail services support IMAP.

3. Secured Mail Access

Like many other protocols, POP and IMAP, exchange login name, password and data in the clear form. This means that anyone having access to the link between the server and client can listen and probably discover passwords. To overcome this problem, it is strongly recommended to use POP and IMAP that operate only through secure channels.

Usually, to make mail access secured, POP and IMAP are bundled with Transport Layer Security (TLS) or Secure Sockets Layer (SSL). Most of the mail servers including Gmail use this mechanism. The POP3 protocol, when used with an SSL layer, is called POP3S. Similarly, the IMAP when bundled with SSL is called IMAPS. A list of port numbers used by these protocols is shown in Table 15.2:

A detailed list of SMTP, POP and IMAP servers may be found in Section 15.14

4. JavaMail API support

Fortunately, JavaMail API supports both of these protocols. In this section, we shall discuss how JavaMail API allows us to retrieve emails from servers that implement POP and/or IMAP.

To describe message storage, JavaMail API provides two primary classes Store and Folder. Messages, delivered by a transport protocol or an agent, are placed in Folders. The Store class describes a Folder hierarchy and an access protocol such as POP, IMAP etc. These access protocols are used to retrieve messages from folders.

5. Reading Email

To read messages, a Store object is first created.

Store store = session.getStore(”pop3s”);

This indicates that store should use the protocol pop3s while retrieving the messages. The protocol pop3s is a secured extension to pop3. Alternatively, imaps (which is a protocol similar to pop3s) may be used:

Store store = session.getStore(”imaps”);

Since, both pop3s and imaps require user name and password to be verified, connect() method is used to supply them:

String host = “pop.gmail.com”, username = “usr.some”, password = “some.usr”;

store.connect(host, username, password);

The connect() method takes a host na^ie, user na^ie, and password to authenticate a user. The name of the POP3 server for Gmail is pop.gmaii.com and is used as host name. There are other overloaded connect() methods where missing information is obtained from the Session object’s properties and Authenticator object.

If everything goes fine, we have an access to the message store now. To access messages, we create a Folder object that represents a folder containing messages. Folders can contain subfolders as well as messages, thus providing a hierarchical structure.

The following program (RetrieveEmail.java) shows how to retrieve all emails of the user usr. some from the Gmail POP3 server pop.gmail.com using Java mail API and POP3.

import java.util.Properties; import javax.mail.*; public class RetrieveEmail {

public static void main(String[] args) throws Exception {

String host = “pop.gmail.com”, protocol = “pop3s”;

String username = “usr.some”, password = “some.usr”;

Properties props = new Properties();

Session session = Session.getInstance(props);

session.setDebug(true);

Store store = session.getStore(protocol);

store.connect(host, username, password);

Folder inbox = store.getFolder(“Inbox”);

if (inbox.exists()) {

inbox.open(Folder.READ_ONLY);

Message[] emails = inbox.getMessages();

for (int i = 0; i < emails.length; i++)                   {

System.out.println(“Message ” + (i + 1));

emails[i].writeTo(System.out);

}

inbox.close(false);

}

else

System.out.println(“Inbox not available”); store.close();

}

}

A sample output of this program is shown in Figure 15.9:

6. Using Authenticator

Like sending emails, an Authenticator object may also be used to retrieve mails. In this case, instead of passing host, user and password to the connect() method of Store directly, we configure a Properties object to have the host, and create an Authenticator object having user and password. These two objects are then supplied to the Session object. The following example demonstrates this:

String host = “pop.gmail.com”, protocol = ”pop3s”;

String username = “usr.some”, password = ”some.usr”;

Properties props = new Properties();

//provide host

props.put(“mail.”+protocol+”.host”, host);

//provide user and password

Authenticator auth = new Authenticator () {

public PasswordAuthentication getPasswordAuthentication(){

return new PasswordAuthentication(user, password);

}

};

Session session = Session.getInstance(props, auth);

Store store = session.getStore(protocol);

store.connect();

The protocol imaps may be used instead of pop3s.

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *