Java
  Home arrow Java arrow Page 4 - Java Mail API: Transforming Mail into Data...
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  
Dedicated Servers  
Actuate Whitepapers 
VeriSign Whitepapers 
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: Transforming Mail into Data Carriers
By: A.P.Rajshekhar
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 5
    2005-11-22

    Table of Contents:
  • Java Mail API: Transforming Mail into Data Carriers
  • Java Mail Core Classes Continued
  • Mails As Data Carriers: A Practical Approach
  • Sending
  • Receiving

  • 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
     
    Iron Speed
     
    ADVERTISEMENT

    Generate data entry and reporting .NET Web apps in minutes, straight from your database. Read our FREE whitepaper “Build Web 2.0 Applications Without Hand-Coding” Download now!

    Java Mail API: Transforming Mail into Data Carriers - Sending


    (Page 4 of 5 )

    That was theory. Now let's see it in practice. This application supposes that the XML document reader and writer are already in place. To send the document as an attachment I will add a function to the MailClient.java -- sendDocument(). It takes a filename and the recipient’s address as String and returns a boolean value corresponding to the success or failure of the transfer. For clarity I am including the complete file.

    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;
      }
      public boolean sendDocument(String filename, String toAddress,  String from,  String subject, String message)
             {
     :
     :
             }
     
    }

    First create an object of MimeMesage and set the from and to addresses as well as the subject. Also set the body of the message.

    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;
      }
      public boolean sendDocument(String filename, String toAddress, String from,  String subject, String message)
             {
     try
           {
         // create a message
         MimeMessage msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress(from));
         InternetAddress[] address = {new InternetAddress(to)};
         msg.setRecipients(Message.RecipientType.TO, address);
         msg.setSubject(subject);
                   
         // create and fill the first message part
         MimeBodyPart mbp1 = new MimeBodyPart();
         mbp1.setText(msgText1);

         // create the second message part
         MimeBodyPart mbp2 = new MimeBodyPart();

     :
     :
         } catch (MessagingException mex) {
         mex.printStackTrace();
         Exception ex = null;
         if ((ex = mex.getNextException()) != null) {
      ex.printStackTrace();
         }

       }
     
    }

    Then create an object of FileDataSource from the file name. Next, set the data handler for the mbp2 object of MimeBodyPart. The data handler reads the data from the file and gives it to the MimeBodyPart. Here I will just show the function.

    public boolean sendDocument(String filename, String toAddress, String from,  String subject, String message)
      {
      try 
      {
         // create a message
         MimeMessage msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress(from));
         InternetAddress[] address = {new InternetAddress(to)};
         msg.setRecipients(Message.RecipientType.TO, address);
         msg.setSubject(subject);
                   
         // create and fill the first message part
         MimeBodyPart mbp1 = new MimeBodyPart();
         mbp1.setText(msgText1);

         // create the second message part
         MimeBodyPart mbp2 = new MimeBodyPart();

         // attach the file to the message
            FileDataSource fds = new FileDataSource(filename);
         mbp2.setDataHandler(new DataHandler(fds));
         mbp2.setFileName(fds.getName());


     :
     :
         } catch (MessagingException mex) {
         mex.printStackTrace();
         Exception ex = null;
         if ((ex = mex.getNextException()) != null) {
      ex.printStackTrace();
         }

    Then create an object of Multipart, add the two MimeBodyPart objects to it, and send the file using send of the Transport class.

    public boolean sendDocument(String filename, String toAddress, String from,  String subject, String message)
       {
       try 
       {
         // create a message
         MimeMessage msg = new MimeMessage(session);
         msg.setFrom(new InternetAddress(from));
         InternetAddress[] address = {new InternetAddress(to)};
         msg.setRecipients(Message.RecipientType.TO, address);
         msg.setSubject(subject);
                   
         // create and fill the first message part
         MimeBodyPart mbp1 = new MimeBodyPart();
         mbp1.setText(msgText1);

         // create the second message part
         MimeBodyPart mbp2 = new MimeBodyPart();

         // attach the file to the message
         FileDataSource fds = new FileDataSource(filename);
         mbp2.setDataHandler(new DataHandler(fds));
         mbp2.setFileName(fds.getName());

         // create the Multipart and add its parts to it
         Multipart mp = new MimeMultipart();
         mp.addBodyPart(mbp1);
         mp.addBodyPart(mbp2);

         // add the Multipart to the message
         msg.setContent(mp);

         // set the Date: header
         msg.setSentDate(new Date());
        
         // send the message
         Transport.send(msg);

         } catch (MessagingException mex) {
         mex.printStackTrace();
         Exception ex = null;
               
         if ((ex = mex.getNextException()) != null) {
      ex.printStackTrace();
         return false;
         }
       return true;
    }

    More Java Articles
    More By A.P.Rajshekhar


       · HiThank you for reading this article. It details about using Mail API as data...
     

    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...

    Iron Speed

    Iron Speed





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway