Home arrow Java arrow Page 4 - Java Mail API: Getting Started
JAVA

Java Mail API: Getting Started


In this article, the first in a multi-part series, you will learn the basics of Java Mail and how to use it for data exchange. This article covers the concepts surrounding different mailing protocols, the APIs that form the basis of Java Mail, and the creation of a class containing common email-related functionalities.

Author Info:
By: A.P.Rajshekhar
Rating: 4 stars4 stars4 stars4 stars4 stars / 43
November 16, 2005
TABLE OF CONTENTS:
  1. · Java Mail API: Getting Started
  2. · Mail Protocols: Rules that Govern Email
  3. · Java Mail: Understanding the API
  4. · Java Mail: Putting it all together

print this article
SEARCH DEVARTICLES

Java Mail API: Getting Started - Java Mail: Putting it all together
(Page 4 of 4 )

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.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials