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