Saturday, April 18, 2009

Know how to send mail using Java Mail API..

The following are the core classes of Java Mail:

1. Session
2. Authenticator
3. Store
4. Folder
5. Message
6. Address
7. Transport

Just like the classes of other Java APIs, the factory class pattern is used in all the above classes. It will be clearer when the classes are discussed. I will be discussing the first four classes in this part as they are the "founding" classes of any Mail application.

1. Session:

Session forms the basis of any client server based application, framework or APIs. The Java Mail API is no exception. The Session class defines a basic mail session. To pass values to the Session object, the Properties object could be used. Since all the constructors of this class are private, a sharable object can be obtained by using the method of the same class -- getDefaultInstance(). This method takes two parameters in its parameterized form -- an object of Properties class, and one of the Authenticator class. The Authenticator will be discussed shortly. So, to get an instance of Session class the code is:
Properties props = new Properties();
// fill props with any information
Session session = Session.getDefaultInstance(props, null);

If a shared instance is not what is required, the getInstance() method to get a unique instance looks like this:
Properties props = new Properties();
// fill props with any information
Session session = Session.getInstance(props, null);

The parameter for Authenticator is supplied as null. This can be done to keep the application simple, but it is not recommended.

2. Authenticator:

As in the case of java.net packages, the Mail APIs can take advantage of the Authenticator class. This class provides access to the protected resources via username and password. The resources can be anything ranging from simple files to servers. For Java Mail, the resource is the server. In essence the Authenticator object passes as a parameter to the getInstance()/getDefaultInstance() method, and controls the security aspect of the Session object.

There are two ways to use the Authenticator. First, you can separately subclass the Authenticator and provide its object to the getInstance()/getDefaultInstance() method. The other way is to subclass the Authenticator by the same class that encapsulates the mailing logic. The following is an example of former approach:
Properties props = new Properties();
// fill props with any information
Authenticator auth = new MyAuthenticator();
Session session = Session.getDefaultInstance(props, auth);

To make use of the other approach the code is:
Properties props = new Properties();
// fill props with any information
Session session = Session.getDefaultInstance(props, this);

3. Store:

This class represents a mail storage. To retrieve messages, one must connect to this store. But before that, an object of the Store class must be obtained, which is done like this:
Store store = session.getStore("pop3");
store.connect(host, username, password);

The getStore() method of Session class provides an instance of Store. The parameter is the protocol to be used. It can be either “imap” for IMAP and “pop3” for POP3. Once the Store object has been obtained, the connect() method can be called with hostname/IP, username and password as parameters to connect to the Store. The connect() has a no parameter form. If the Authenticator’s object has been passed to the getInstance()/getDefaultInstance() along with the Properties object containing the hostname, then the no parameter form can be used.

4. Folder:

All the messages belonging to a particular user are placed inside a Folder within the Store. The Folder represents such a folder. As is the case with Store, an object of Folder could be obtained by calling the getFolder() method of the Store class. The getFolder() method takes only one parameter -- the name of the folder to be opened as a string. To open the inbox pass “INBOX” as the parameter. In code:
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);

Once the instance of Folder has been obtained, calling the open method on that instance will actually open the folder. Once opened, the messages can be retrieved. The open() method accepts one parameter representing the state in which the folder has to be opened. The constants provided in the Folder class can be used to provide the required state. Of the available states the most common are “read only” represented by Folder.READ_ONLY and “read write” represented by Folder.READ_WRITE.

Now we will see how to put it all together as a class that can be extended and reused. So let's get started.

Start with the package name.

package ap.mail;

Then come the imports.
package ap.mail;
import ap.mail.MailAuthenticator;
import com.sun.mail.iap.Protocol;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;
import java.util.Hashtable;
import org.apache.james.userrepository.DefaultJamesUser;
import org.apache.james.services.UsersStore;

The last two imports are important if the password authenticator has to be used.

Next is the class. The class must subclass the Authenticator, as the class itself would implement the logic for password authentication.
public class MailClient extends Authenticator
{
:
:
}

The variables to be used across the methods have to be declared.

public class MailClient extends Authenticator
{
protected String from;
protected Session session;
protected PasswordAuthentication authentication;
protected Folder rootFolder,currentFolder;
protected Store store;
:
}

Then comes the constructor. Since the Properties will be used to pass the information regarding the host username and password, the object of the Properties class would be instantiated here.

public class MailClient extends Authenticator
{
protected String from;
protected Session session;
protected PasswordAuthentication authentication;
protected Folder rootFolder,currentFolder;
protected Store store;

public MailClient(String user, String host, boolean debug,String password)
{
from = user + '@' + host;
authentication = new PasswordAuthentication(user, password);
Properties props = new Properties();
props.put("mail.user", user);
props.put("mail.host", host);
props.put("mail.debug", debug ? "true" : "false");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
session = Session.getInstance(props, this);
}

:
}

To provide the authentication support, the getPasswordAuthenticator() method has to be overridden. Since this application would not provide its own implementation, this method would just return an object of type PasswordAuthentication.

public class MailClient extends Authenticator
{
protected String from;
protected Session session;
protected PasswordAuthentication authentication;
protected Folder rootFolder,currentFolder;
protected Store store;

public MailClient(String user, String host, boolean debug,String password)
{
from = user + '@' + host;
authentication = new PasswordAuthentication(user, password);
Properties props = new Properties();
props.put("mail.user", user);
props.put("mail.host", host);
props.put("mail.debug", debug ? "true" : "false");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
session = Session.getInstance(props, this);
}
public PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}

:
}



The next step is to connect to the store.

public class MailClient extends Authenticator
{
protected String from;
protected Session session;
protected PasswordAuthentication authentication;
protected Folder rootFolder,currentFolder;
protected Store store;

public MailClient(String user, String host, boolean debug,String password)
{
from = user + '@' + host;
authentication = new PasswordAuthentication(user, password);
Properties props = new Properties();
props.put("mail.user", user);
props.put("mail.host", host);
props.put("mail.debug", debug ? "true" : "false");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
session = Session.getInstance(props, this);
}
public PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
public boolean connectToStore()
{
boolean connected=false;
try
{
store = session.getStore();
store.connect();
rootFolder = store.getDefaultFolder();
openFolder("INBOX");
connected=true;
}
catch (NoSuchProviderException e)
{
e.printStackTrace();
}
catch (MessagingException e)
{
e.printStackTrace();
}
return connected;
}

:
}

Once the connection to the store has been established, to extract the messages, the folder has to be opened. That is done like this:

public class MailClient extends Authenticator
{
protected String from;
protected Session session;
protected PasswordAuthentication authentication;
protected Folder rootFolder,currentFolder;
protected Store store;

public MailClient(String user, String host, boolean debug,String password)
{
from = user + '@' + host;
authentication = new PasswordAuthentication(user, password);
Properties props = new Properties();
props.put("mail.user", user);
props.put("mail.host", host);
props.put("mail.debug", debug ? "true" : "false");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
session = Session.getInstance(props, this);
}
public PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
public boolean connectToStore()
{
boolean connected=false;
try
{
store = session.getStore();
store.connect();
rootFolder = store.getDefaultFolder();
openFolder("INBOX");
connected=true;
}
catch (NoSuchProviderException e)
{
e.printStackTrace();
}
catch (MessagingException e)
{
e.printStackTrace();
}
return connected;
}
public boolean openFolder(String folder)
{
boolean isOpenend=false;
try
{
currentFolder = rootFolder.getFolder(folder);
currentFolder.open(Folder.READ_WRITE);
isOpenend=true;
}
catch (MessagingException e)
{
e.printStackTrace();
}
return isOpenend;
}

}

That’s it. This class can now connect to a mail server. In this case, it connects to an Apache James Server. And this brings this discussion to its conclusion. In this part the discussion was focused on the basics of Java Mail. The next part will focus on APIs that help applications send huge amounts of data, and on how to actually achieve this end. Till next time.

1 comment:

  1. Hi Friends
    M a beginner working for WPF
    m asked to diplay a time out msg once the portal session expires.. asking user to login again.. plsss help me on this task.. aslo wish to kno how portal session is diff from poge session management!! knidly reply back.........

    ReplyDelete