3 Replies Latest reply on Feb 26, 2002 3:42 PM by 807555

    How do I read a Email from the MS exchange server

    807555
      could any one tell me as to how i could read the mail from the exchange server and store it in a seperate folder.
        • 1. Re: How do I read a Email from the MS exchange server
          807555
          For example with the help of JavaMail, part of EE but available also separately.
          • 2. Re: How do I read a Email from the MS exchange server
            807555
            pls could you let me know where could i find the code
            • 3. Re: Error in accessing the mails from the exchange server
              807555
              I have an application which reads the mail from our mail server and then writes the body of the message into a file and then deletes the email anf those values are then read from that file and stored into the database .
              Here is the code which pops the mail from the exchange server and then stores it into a file .
              ----------
              import javax.mail.*;
              import com.sun.mail.pop3.*;
              import javax.mail.internet.*;
              import javax.activation.*;
              import java.util.*;

              /**
              * Title:
              * Description:
              * Copyright: Copyright (c) 2001
              * Company:
              * @author
              * @version 1.0
              */

              public class SunMailConnection implements Runnable{
                   boolean suspendFlag;
                   ErrorLogWriter log = new ErrorLogWriter("SunMail.log");

                   public SunMailConnection() {
                        this.start() ;
                   }


                   public void run(){

                        try {
                             int start = 1;int end = -1;
                             String host = "cyde-cehh-exh1";//the local exchange server name AND DOESNT WORK IF U CONNECT TO EXT MAIL SERVER DIRECTLY
                             //DUE TO SECURED AUTHORISATION

                             //String host ="http://www.conergy-electronics.de";
                             String username ="SunReader\\Sun\\saa";
                             String password = "xxxxx";

                             // Create empty properties
                             Properties props = new Properties();
                             props.put("mail.protocol.store","pop3");
                             // Get session
                             Session session = Session.getDefaultInstance(props, null);
                             Provider[] p = session.getProviders();
                             //for (int i=0;i<p.length;i++) System.out.println(p.getProtocol());

                             // Get the store
                             Store store = session.getStore("pop3");
                             store.connect(host, username, password);


                             // Get folder
                             Folder folder = store.getFolder("INBOX");

                             if (folder == null || !folder.exists()) {
                                  //System.out.println("Invalid folder: " + folder.getName());
                                  log.write("Invalid folder: " + folder.getName()) ;
                                  System.exit(1);
                             }

                             folder.open(Folder.READ_WRITE);

                             //Get the number of Unread Messages
                             int count = folder.getUnreadMessageCount();

                             if (count == 0) { // No messages in the source folder
                                  //System.out.println(folder.getName() + " is empty");
                                  // Close folder, store and return
                                  folder.close(false);
                                  store.close();
                                  return;
                             }

                             if (end == -1)
                                  end = count;


                             // Get the message objects to copy
                             log.write("Test");
                             Message[] msgs = folder.getMessages(start, end);
                             //System.out.println("Moving " + msgs.length + " messages");
                             //log.write("Moving " + msgs.length + " messages") ;


                             if (msgs.length != 0) {
                                  //If there is any mail
                                  //System.out.println(msgs.length );
                                  //read mail from server into files
                                  MoveMessageTo saveFile = new MoveMessageTo(msgs);

                                  if(saveFile.createdFile=true){
                                       folder.setFlags(msgs,new Flags(Flags.Flag.SEEN),true);
                                       //delete flag set here to remove the email from INBOX
                                       folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);

                                  }
                                  //folder.expunge(); //removes messages marked as deleted
                                  //check for deleting messages
                                  for (int i = 0; i < msgs.length; i++) {
                                       if (!msgs[i].isSet(Flags.Flag.DELETED))
                                            log.write("Message # "+msgs[i]+" not deleted.");
                                       //else System.out.println("Message "+i+"-is deleted") ;
                                  }
                             }


                             // Close connection
                             folder.close(true);
                             // dfolder.close(false);
                             store.close();
                             //this.start() ;

                        }catch (Exception ex) {
                             ex.printStackTrace() ;
                        }
                        //this.t.start();
                   }
                   public void start(){
                        try {
                             while(this!= null){
                                  this.run() ;
                                  Thread.sleep(15000);//every 15 seconds
                             }
                        }catch (Exception ex) {
                             ex.printStackTrace();
                        }
                   }
                   public void exit(){

                        this.exit();
                        System.out.println("Exit");

                   }

                   public static void main(String[] args) {
                        SunMailConnection sunMail = new SunMailConnection();
                   }
              }
              ----------------
              This is to show the messages

              import java.util.*;
              import java.io.*;
              import javax.mail.*;
              import javax.mail.internet.*;
              import javax.activation.*;


              public class msgshow {

              static String protocol;
              static String host = null;
              static String user = null;
              static String password = null;
              static String mbox = "INBOX";
              static String url = null;
              static int port = -1;
              static boolean verbose = false;
              static boolean debug = false;
              static boolean showStructure = false;
              static boolean showMessage = false;

              public static void main(String argv[]) {
                   int msgnum = -1;
                   int optind;
                   protocol = "pop3";
                   host="cyde-cehh-exh1";
                   user="SunReader\\Sun\\saa";
                   password="xxxxxx";
                   mbox="INBOX";
                   /*for (optind = 0; optind < argv.length; optind++) {
                   if (argv[optind].equals("-T")) {
                        protocol = argv[++optind];
                   } else if (argv[optind].equals("-H")) {
                        host = argv[++optind];
                   } else if (argv[optind].equals("-U")) {
                        user = argv[++optind];
                   } else if (argv[optind].equals("-P")) {
                        password = argv[++optind];
                   } else if (argv[optind].equals("-v")) {
                        verbose = true;
                   } else if (argv[optind].equals("-D")) {
                        debug = true;
                   } else if (argv[optind].equals("-f")) {
                        mbox = argv[++optind];
                   } else if (argv[optind].equals("-L")) {
                        url = argv[++optind];
                   } else if (argv[optind].equals("-p")) {
                        port = Integer.parseInt(argv[++optind]);
                   } else if (argv[optind].equals("-s")) {
                        showStructure = true;
                   } else if (argv[optind].equals("-m")) {
                        showMessage = true;
                   } else if (argv[optind].equals("--")) {
                        optind++;
                        break;
                   } else if (argv[optind].startsWith("-")) {
                        System.out.println(
              "Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
                        System.out.println(
              "\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s]");
                        System.out.println(
              "or msgshow -m [-v] [-D] [-s] < msg");
                        System.exit(1);
                   } else {
                        break;
                   }
                   }*/

                   try {
                   // if (optind < argv.length)
                   // msgnum = Integer.parseInt(argv[optind]);
                        //msgnum = 5;

                   // Get a Properties object
                   Properties props = System.getProperties();

                   // Get a Session object
                   Session session = Session.getDefaultInstance(props, null);
                   session.setDebug(debug);

                   if (showMessage) {
                        MimeMessage msg = new MimeMessage(session, System.in);
                        dumpPart(msg);
                        System.exit(0);
                   }

                   // Get a Store object
                   Store store = null;
                   if (url != null) {
                        URLName urln = new URLName(url);
                        store = session.getStore(urln);
                        store.connect();
                   } else {
                        if (protocol != null)
                        store = session.getStore(protocol);
                        else
                        store = session.getStore();

                        // Connect
                        if (host != null || user != null || password != null)
                        store.connect(host, port, user, password);
                        else
                        store.connect();
                   }


                   // Open the Folder

                   Folder folder = store.getDefaultFolder();
                   if (folder == null) {
                        System.out.println("No default folder");
                        System.exit(1);
                   }

                   folder = folder.getFolder(mbox);
                   if (folder == null) {
                        System.out.println("Invalid folder");
                        System.exit(1);
                   }

                   // try to open read/write and if that fails try read-only
                   try {
                        folder.open(Folder.READ_WRITE);
                   } catch (MessagingException ex) {
                        folder.open(Folder.READ_ONLY);
                   }
                   int totalMessages = folder.getMessageCount();

                   if (totalMessages == 0) {
                        System.out.println("Empty folder");
                        folder.close(false);
                        store.close();
                        System.exit(1);
                   }

                   if (verbose) {
                        int newMessages = folder.getNewMessageCount();
                        System.out.println("Total messages = " + totalMessages);
                        System.out.println("New messages = " + newMessages);
                        System.out.println("-------------------------------");
                   }

                   if (msgnum == -1) {
                        // Attributes & Flags for all messages ..
                        Message[] msgs = folder.getMessages();

                        // Use a suitable FetchProfile
                        FetchProfile fp = new FetchProfile();
                        fp.add(FetchProfile.Item.ENVELOPE);
                        fp.add(FetchProfile.Item.FLAGS);
                        fp.add("X-Mailer");
                        folder.fetch(msgs, fp);

                        for (int i = 0; i < msgs.length; i++) {
                        System.out.println("--------------------------");
                        System.out.println("MESSAGE #" + (i + 1) + ":");
                        dumpEnvelope(msgs[i]);
                        // dumpPart(msgs[i]);
                        }
                   } else {
                        System.out.println("Getting message number: " + msgnum);
                        Message m = null;

                        try {
                        m = folder.getMessage(msgnum);
                        dumpPart(m);
                        } catch (IndexOutOfBoundsException iex) {
                        System.out.println("Message number out of range");
                        }
                   }

                   folder.close(false);
                   store.close();
                   } catch (Exception ex) {
                   System.out.println("Oops, got exception! " + ex.getMessage());
                   ex.printStackTrace();
                   System.exit(1);
                   }
                   System.exit(0);
              }

              public static void dumpPart(Part p) throws Exception {
                   if (p instanceof Message)
                   dumpEnvelope((Message)p);

                   /** Dump input stream ..

                   InputStream is = p.getInputStream();
                   // If "is" is not already buffered, wrap a BufferedInputStream
                   // around it.
                   if (!(is instanceof BufferedInputStream))
                   is = new BufferedInputStream(is);
                   int c;
                   while ((c = is.read()) != -1)
                   System.out.write(c);

                   **/

                   pr("CONTENT-TYPE: " + p.getContentType());
                   String filename = p.getFileName();
                   if (filename != null)
                   pr("FILENAME: " + filename);

                   /*
                   * Using isMimeType to determine the content type avoids
                   * fetching the actual content data until we need it.
                   */
                   if (p.isMimeType("text/plain")) {
                   pr("This is plain text");
                   pr("---------------------------");
                   if (!showStructure)
                        System.out.println((String)p.getContent());
                   } else if (p.isMimeType("multipart/*")) {
                   pr("This is a Multipart");
                   pr("---------------------------");
                   Multipart mp = (Multipart)p.getContent();
                   level++;
                   int count = mp.getCount();
                   for (int i = 0; i < count; i++)
                        dumpPart(mp.getBodyPart(i));
                   level--;
                   } else if (p.isMimeType("message/rfc822")) {
                   pr("This is a Nested Message");
                   pr("---------------------------");
                   level++;
                   dumpPart((Part)p.getContent());
                   level--;
                   } else if (!showStructure) {
                   /*
                   * If we actually want to see the data, and it's not a
                   * MIME type we know, fetch it and check its Java type.
                   */
                   Object o = p.getContent();
                   if (o instanceof String) {
                        pr("This is a string");
                        pr("---------------------------");
                        System.out.println((String)o);
                   } else if (o instanceof InputStream) {
                        pr("This is just an input stream");
                        pr("---------------------------");
                        InputStream is = (InputStream)o;
                        int c;
                        while ((c = is.read()) != -1)
                        System.out.write(c);
                   } else {
                        pr("This is an unknown type");
                        pr("---------------------------");
                        pr(o.toString());
                   }
                   } else {
                   pr("This is an unknown type");
                   pr("---------------------------");
                   }
              }

              public static void dumpEnvelope(Message m) throws Exception {
                   pr("This is the message envelope");
                   pr("---------------------------");
                   Address[] a;
                   // FROM
                   if ((a = m.getFrom()) != null) {
                   for (int j = 0; j < a.length; j++)
                        pr("FROM: " + a[j].toString());
                   }

                   // TO
                   if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
                   for (int j = 0; j < a.length; j++)
                        pr("TO: " + a[j].toString());
                   }

                   // SUBJECT
                   pr("SUBJECT: " + m.getSubject());

                   // DATE
                   Date d = m.getSentDate();
                   pr("SendDate: " +
                   (d != null ? d.toString() : "UNKNOWN"));



                   // FLAGS
                   Flags flags = m.getFlags();
                   StringBuffer sb = new StringBuffer();
                   Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags

                   boolean first = true;
                   for (int i = 0; i < sf.length; i++) {
                   String s;
                   Flags.Flag f = sf[i];
                   if (f == Flags.Flag.ANSWERED)
                        s = "\\Answered";
                   else if (f == Flags.Flag.DELETED)
                        s = "\\Deleted";
                   else if (f == Flags.Flag.DRAFT)
                        s = "\\Draft";
                   else if (f == Flags.Flag.FLAGGED)
                        s = "\\Flagged";
                   else if (f == Flags.Flag.RECENT)
                        s = "\\Recent";
                   else if (f == Flags.Flag.SEEN)
                        s = "\\Seen";
                   else
                        continue;     // skip it
                   if (first)
                        first = false;
                   else
                        sb.append(' ');
                   sb.append(s);
                   }

                   String[] uf = flags.getUserFlags(); // get the user flag strings
                   for (int i = 0; i < uf.length; i++) {
                   if (first)
                        first = false;
                   else
                        sb.append(' ');
                   sb.append(uf[i]);
                   }
                   pr("FLAGS: " + sb.toString());

                   // X-MAILER
                   String[] hdrs = m.getHeader("X-Mailer");
                   if (hdrs != null)
                   pr("X-Mailer: " + hdrs[0]);
                   else
                   pr("X-Mailer NOT available");
              }

              static String indentStr = " ";
              static int level = 0;

              /**
              * Print a, possibly indented, string.
              */
              public static void pr(String s) {
                   if (showStructure)
                   System.out.print(indentStr.substring(0, level * 2));
                   System.out.println(s);
              }
              }
              ---------------------------
              This code is to move the message into a file

              import javax.mail.*;
              import com.sun.mail.pop3.*;
              import javax.mail.internet.*;
              import javax.activation.*;
              import java.util.*;
              import java.io.*;


              //This class copies the content of the received e-mail into files. The file names are given by
              //the urgent flag value and the subject

              public class MoveMessageTo {
                   boolean createdFile = true;
                   static final byte urgentFlagPos=13;
                   public MoveMessageTo() {
                   }

                   public MoveMessageTo(Message[] msgs) {

                        if(msgs.length != 0)
                        try {
                             for(int i = 0;i<msgs.length ;i++){
                                  //Reads the content of the mail into an Object
                                  Object currMultipart = msgs[i].getContent();
                                  //converts this object into a String and then to a byte array, so we can read the urgnet flag
                                  String content=(String)currMultipart;

                                  byte[] testBytes=content.getBytes();
                                  //The urgent flag is the first digit in the filename
                                  StringBuffer fileName=new StringBuffer();
                                  if (testBytes.length>urgentFlagPos)
                                       fileName.append(new Byte(testBytes[urgentFlagPos]).toString());
                                  //Then comes the subject of the e-mail
                                  String mailSubject=msgs[i].getSubject();
                                  if (mailSubject.length()>0)
                                       fileName.append(mailSubject);
                                  else fileName.append("noSubject");
                                  fileName.append(".dat");

                                  //create a directory to save the files
                                  File baseDir = new File("c:/EMails/New");
                                  baseDir.mkdirs();

                                  //create file for with the subject as name
                                  File eFile = new File(baseDir+"/"+fileName.toString());// creates a file by name of email subject

                                  //Opening an stream for writting to the files
                                  BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(eFile));
                                  ObjectOutputStream oos = new ObjectOutputStream(bos);
                                  //Writing the message body to the file
                                  oos.writeObject(currMultipart) ;
                                  //Closing the stream
                                  oos.flush() ;
                                  oos.close() ;
                                  createdFile = true;
                             }

                        }catch (Exception ex) {
                             createdFile = false;
                             System.out.println("eFile is not created ");
                             ex.printStackTrace() ;
                        }
                   }

                   public static void main(String[] args) {
                        MoveMessageTo moveMessageTo1 = new MoveMessageTo();
                   }
              ----------------------
              This code is if there is an error in reading a file it will write those error into the file

              import java.io.*;
              import javax.swing.*;
              import java.awt.Color;
              import javax.swing.border.*;

              //This class appends an error message to the log file
              public class ErrorLogWriter {
                   //JPanel jPanel2 = new JPanel();
                   //Border border1;
                   String logDirectory="c:/EMails/log/";
                   File errFile; //= new File(errDir+"/"+"errorLog.dat");

                   //The constructor initializes the errFile given the filename
                   public ErrorLogWriter(String fileName) {
                        errFile=new File(logDirectory+fileName);
                        /*try {
                             jbInit();
                        }catch(Exception e) {
                             e.printStackTrace();
                        }*/
                   }

                   public void write(String writeStr){
                        try {
                             //Creates directory if doesn't exist
                             File errDir = new File(logDirectory);
                             errDir.mkdirs() ;
                             //If the directory exists...
                             if(errDir.isDirectory()){
                                  //File errFile = new File(errDir+"/"+"errorLog.dat");
                                  byte[] lastContent=new byte[0];
                                  //If there is already a file with this name: Read its content so it can be preserved
                                  if (errFile.exists()){
                                       FileInputStream fis=new FileInputStream(errFile);
                                       //Read everything into the byte array
                                       lastContent=new byte[fis.available()];
                                       fis.read(lastContent);
                                  }

                                  BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(errFile));
                                  PrintWriter oos = new PrintWriter(bos);
                                  String newWriteString=new String(lastContent);
                                  writeStr.trim() ;
                                  //Appends the new string to the old content
                                  newWriteString+=writeStr;
                                  newWriteString+="\n";
                                  //writes everthing back to the file
                                  oos.write(newWriteString) ;
                                  oos.flush();
                                  oos.close();
                             }
                        }catch (Exception ex) {
                             ex.printStackTrace() ;
                        }
                   }

                   public static void main(String[] args) {
                        ErrorLogWriter log = new ErrorLogWriter("logerror.log");
                        log.write("Hello Log!") ;
                   }

                   }
              -----------------------------------
              All these file are in one package called SunMail and i run this in jbuilder in 4.0 ,I get the following error

              eFile is not created

              java.lang.ClassCastException: javax.mail.internet.MimeMultipart

                   at MoveMessageTo.<init>(MoveMessageTo.java:26)

                   at SunMailConnection.run(SunMailConnection.java:86)

                   at SunMailConnection.start(SunMailConnection.java:118)

                   at SunMailConnection.<init>(SunMailConnection.java:21)

                   at SunMailConnection.main(SunMailConnection.java:133)

              I know the it would be difficult if anyone could help me out it would be a great favour !!!
              pls help me out of this !!!!