Home arrow Java arrow Page 4 - Java Mail API: Transforming Mail into Data Carriers
JAVA

Java Mail API: Transforming Mail into Data Carriers


Java Mail is eminently adaptable. Indeed, looking at its API, we find that it helps us provide an alternative solution to an old problem: how to transfer large amounts of data between two enterprise applications. In this article, you will discover how to adapt Java Mail to play the role of a data carrier.

Author Info:
By: A.P.Rajshekhar
Rating: 5 stars5 stars5 stars5 stars5 stars / 6
November 22, 2005
TABLE OF CONTENTS:
  1. · Java Mail API: Transforming Mail into Data Carriers
  2. · Java Mail Core Classes Continued
  3. · Mails As Data Carriers: A Practical Approach
  4. · Sending
  5. · Receiving

print this article
SEARCH DEVARTICLES

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;
}


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