Java
  Home arrow Java arrow Page 4 - Java Mail API: Getting Started
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVA

Java Mail API: Getting Started
By: A.P.Rajshekhar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 30
    2005-11-16

    Table of Contents:
  • Java Mail API: Getting Started
  • Mail Protocols: Rules that Govern Email
  • Java Mail: Understanding the API
  • Java Mail: Putting it all together

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    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.

       · HiThank you for reading my article. What I have tried to do is to look at Mail API...
       · Very helpful. Thank you for taking the time to share your knowledge.
       · Thank you for your valuable comments. Readers like you encourage me to write.
     

    JAVA ARTICLES

    - 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 ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT