Read mail from pst outlook file and then send all on some e-mail account using Java

This program will first read all e-mails in pst file and then send one by one to the mail account where you want to send them.
----------------------------------------------------------------

package example;


import com.pff.*;
import java.util.*;
import java.io.*;
import java.net.UnknownHostException;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.internet.*;
import javax.activation.*;
import com.sun.mail.smtp.SMTPMessage;


public class Test {
public static final String host="smtp.gmail.com";
public static final String FROM_ADDRESS = "//enter sender's mail";
public static final String TO_ADDRESS ="//enter recipent mail";
public static final String MAIL_SERVER = "smtp.gmail.com";
public static final String USERNAME ="//Sende email address";
public static final String PASSWORD = "//enter your password";
    public String BODY; 
    public String Sender;
public String Recipient;
public String DestHost;
public String DestAddr;

Properties properties = new Properties();
 
public static void main(String[] args){
new Test("C:/NewWorkSpace/outlook.pst");
}


public Test(String filename) {
try {
System.out.println("File to be read:"+filename);
PSTFile pstFile = new PSTFile(filename);
System.out.println(pstFile.getMessageStore().getDisplayName());
processFolder(pstFile.getRootFolder());
} catch (Exception err) {
err.printStackTrace();
}
}


int depth = -1;
public void processFolder(PSTFolder folder)
throws PSTException, java.io.IOException
{
depth++;
// the root folder doesn't have a display name
if (depth > 0) {
printDepth();
System.out.println("--Folder Display Name--"+folder.getDisplayName());
}


// go through the folders...
if (folder.hasSubfolders()) {
Vector<PSTFolder> childFolders = folder.getSubFolders();
for (PSTFolder childFolder : childFolders) {
processFolder(childFolder);
}
}
        
// and now the emails for this folder
if (folder.getContentCount() > 0) {
boolean flag=true;
depth++;
PSTMessage email = (PSTMessage)folder.getNextChild();
properties.put("mail.smtp.host", MAIL_SERVER);
           properties.put("mail.transport.protocol", "smtp");
           
            Session session = Session.getInstance(properties);
while (email != null) {
printDepth();
System.out.println("From: "+email.getSenderEmailAddress());
System.out.println("\t-To: "+email.getDisplayTo());
System.out.println("\t-CC: "+email.getDisplayCC());
System.out.println("\t-BCC: "+email.getDisplayBCC());
System.out.println("\t-Subject: "+email.getSubject());
System.out.println("\t-Message: "+email.getBody());
Sender=email.getSenderEmailAddress();
Recipient=email.getDisplayTo();
try{
InternetAddress[] address = {new InternetAddress(USERNAME)};
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(TO_ADDRESS));
                msg.setRecipients(Message.RecipientType.TO, address);
             
                msg.setRecipients(Message.RecipientType.CC,
                InternetAddress.parse(email.getDisplayCC(), true));
                msg.setRecipients(Message.RecipientType.BCC,
                               InternetAddress.parse(email.getDisplayBCC(), true));
                MimeBodyPart p1 = new MimeBodyPart();
               
                BODY=email.getBody();
                System.out.println("====================================================");
                System.out.println("Body::  "+BODY);
                p1.setText(newMessage());
                System.out.println("Body with enevelope::"+newMessage());
                
                System.out.println("====================================================");
                
                Multipart mp = new MimeMultipart();
                mp.addBodyPart(p1);
                msg.setContent(mp,"text/html; charset=UTF-8");
                int numberOfAttachments = email.getNumberOfAttachments();
                if(email.hasAttachments()){
                     PSTAttachment pstAttach = email.getAttachment(0);
                String file =pstAttach.getLongFilename();
                pstAttach.getAttachmentContentDisposition();
                MimeBodyPart p2 = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(file);
                     p2.setDataHandler(new DataHandler(fds));
                     p2.setFileName(fds.getName());
                     Multipart mp1 = new MimeMultipart();
                     mp1.addBodyPart(p2);
                     msg.setContent(mp1,"text/html; charset=UTF-8");                                
                String file1=pstAttach.getPathname();
                System.out.println("Attacment and File name"+numberOfAttachments+""+file+"PathName"+file1);
                  }
                  msg.setSubject(email.getSubject());
                  msg.setFlag(Flag.ANSWERED, email.hasReplied());
                  msg.setFlag(Flag.FLAGGED, email.isFlagged());
                  msg.setFlag(Flag.SEEN, email.isRead());
                  msg.saveChanges();  
           
                 
                  Transport transport = session.getTransport("smtps");
             transport.connect(MAIL_SERVER, USERNAME, PASSWORD);
             transport.sendMessage(msg, address);
             transport.close();
                
             //Transport.send(msg,address);
             System.out.println("Mesaage Successfully sent");
                
}catch (MessagingException mex) {                
                    mex.printStackTrace();                 
                    while (mex.getNextException() != null) {                       
                        Exception ex = mex.getNextException();
                        ex.printStackTrace();
                        if (!(ex instanceof MessagingException)) break;
                        else mex = (MessagingException)ex;
                    }
                }
email = (PSTMessage)folder.getNextChild();
}
depth--;
}else{
System.out.println("===No email==");
}
depth--;
}
public void printDepth() {
for (int x = 0; x < depth-1; x++) {
System.out.print(" | ");
}
System.out.print(" |- ");
}

public String newMessage() {
String res = "Sender: " + Sender + '\n';
res += "Recipient: " + Recipient + '\n';
res += "MX-host: " + DestHost + ", address: " + DestAddr + '\n';
res += "Message:" + '\n';
res += BODY.toString();
return res;
   }

}
-------------------------------------------------------------------------------------------
****Note: Please download required jar and add into your lib or classpath (if you are using eclipse then add these into Java build path-->Liberary-->add external jar)
1) java-libpst.0.7.jar
2) mail.jar 
3) jpst.jar
4) activation-1.1-sources.jar

Comments

  1. Thank you very much for a wonderful and informative Article. I came across a Java email component by the name of Aspose.Email for Java . It also gives you the tools you need to create, read and manipulate Outlook MSG, PST, EML and MHT files from within a Java application.

    ReplyDelete

Post a Comment

Popular posts from this blog

Read Images from a xlsx file using Apache POI

Struts 2 : Warning :No configuration found for the specified action: 'Login.action' in namespace: '/'

How to create mail message in FRC822 format