hello friends,

we have stuck with one problem while doing program of mail api.
we have doing unread mails via mail api,but its not perfectly working.
There is an problem in reading content of (multipart type) of mail. it will work on Text/Plain type.
Following is my code.please let me know,how can read content of a multipart of mail and print it on frame/cmd.

Code:

/*
 * DesktopApplication3View.java
 */

package desktopapplication3;

import com.sun.org.apache.bcel.internal.generic.BREAKPOINT;
import java.io.IOException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.Session;
import javax.mail.Store;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * The application's main frame.
 */
public class DesktopApplication3View extends FrameView {
    Folder inbox;
     String mail;
     String password;
     String from;
     String content;
 //Constructor of the calss.
 public void Mailsender()
 {
 /*  Set the mail properties  */
 Properties props = System.getProperties();
 props.setProperty("mail.store.protocol", "imaps");
 try
 {
 /*  Create the session and get the store for read the mail. */
 Session session = Session.getDefaultInstance(props, null);
 Store store = session.getStore("imaps");
 store.connect("imap.gmail.com",mail,password);

 /*  Mention the folder name which you want to read. */
 inbox = store.getFolder("Inbox");
 System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());

 /*Open the inbox using store.*/
 inbox.open(Folder.READ_ONLY);

 /*  Get the messages which is unread in the Inbox*/
 Message messages[] = inbox.search(new javax.mail.search.FlagTerm(new Flags(Flag.SEEN), false));

 /* Use a suitable FetchProfile    */
 FetchProfile fp = new FetchProfile();
 fp.add(FetchProfile.Item.ENVELOPE);
 fp.add(FetchProfile.Item.CONTENT_INFO);
 inbox.fetch(messages, fp);

 try
 {
 printAllMessages(messages);
 inbox.close(true);
 store.close();
 }
 catch (Exception ex)
 {
 System.out.println("Exception arise at the time of read mail");
 ex.printStackTrace();
 }
 }
 catch (NoSuchProviderException e)
 {
 e.printStackTrace();
 System.exit(1);
 }
 catch (MessagingException e)
 {
 e.printStackTrace();
 System.exit(2);
 }
 }

 public void printAllMessages(Message[] msgs) throws Exception
 {
 for (int i = 0; i < msgs.length; i++)
 {
 System.out.println("MESSAGE #" + (i + 1) + ":");
 printEnvelope(msgs[i]);
 }
 }
public void printEnvelope(Message message) throws Exception
 {
 Address[] a;
 // FROM
 if ((a = message.getFrom()) != null)
 {

 for (int j = 0; j < a.length; j++)
 {
 System.out.println("FROM: " + a[j].toString());
 }
 }
 // TO
 if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
 {
 for (int j = 0; j < a.length; j++)
 {
 System.out.println("TO: " + a[j].toString());
 }
 }
 String subject = message.getSubject();
 Date receivedDate = message.getReceivedDate();
 content = message.getContent().toString();
 System.out.println("Subject : " + subject);
 System.out.println("Received Date : " + receivedDate.toString());
 System.out.println("Content : " + content);
getContent1(message);
// File f1 = new File("D:\\p\\"+subject+".html");
//BufferedWriter out = new BufferedWriter(new FileWriter(f1));
 //out.write(content);
//out.close();
smatching(content,subject);
editorpaneHTML page = new editorpaneHTML(content);
page.setVisible(true);

//     System.out.println("Text File Created");
 }
public void smatching(String content, String Sub)
    {
     String T, P, cand;
     int pos, i;
     P =  "Win";

     System.out.println();

     for ( pos = 0; pos <= content.length() - P.length(); pos++ )
     {
        cand = content.substring( pos, pos+P.length() );

        if ( P.equals(cand) )
        {
           //System.out.println(T);        // Print the text
   JOptionPane.showMessageDialog(mainPanel, "Spam With Subject :"+Sub);
           for ( i = 0 ; i < pos; i++ )  // Indent to found position
           System.out.print(" ");

           System.out.println(P);        // Print the pattern below
           System.out.println();
              // JOptionPane.showMessageDialog(mainPanel, " Content :"+content);

        }
     }


}
 public void getContent1(Message msg)
 {
 try
 {
 String contentType = msg.getContentType();
 System.out.println("Content Type : " + contentType);
 if(contentType.equalsIgnoreCase("TEXT/PLAIN")){}
 else{
 Multipart mp = (Multipart) msg.getContent();
 mp.toString();
 int count = mp.getCount();
 for (int i = 0; i < count; i++)
 {
 dumpPart(mp.getBodyPart(i));

 }
 }
     }
 catch (Exception ex)
 {
 System.out.println("Exception arise at get Content");
 ex.printStackTrace();
 }

 }

 public void dumpPart(Part p) throws Exception
 {
 // 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;
 System.out.println("Message : ");
 while ((c = is.read()) != -1)
 {
 System.out.write(c);
 }
 }


    public DesktopApplication3View(SingleFrameApplication app) {
        super(app);

        initComponents();

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String)(evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer)(evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = DesktopApplication3.getApplication().getMainFrame();
            aboutBox = new DesktopApplication3AboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        DesktopApplication3.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jPasswordField1 = new javax.swing.JPasswordField();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(desktopapplication3.DesktopApplication3.class).getContext().getResourceMap(DesktopApplication3View.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jTextField1.setText(resourceMap.getString("jTextField1.text")); // NOI18N
        jTextField1.setName("jTextField1"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jPasswordField1.setText(resourceMap.getString("jPasswordField1.text")); // NOI18N
        jPasswordField1.setName("jPasswordField1"); // NOI18N

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPasswordField1)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE))
                .addContainerGap(312, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addGap(49, 49, 49)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addContainerGap(120, Short.MAX_VALUE))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(desktopapplication3.DesktopApplication3.class).getContext().getActionMap(DesktopApplication3View.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 397, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       mail = jTextField1.getText();
       password =jPasswordField1.getText();
       Mailsender();
    }                                        

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration                   

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
}

and i got the following output with error.

error:

run:
No of Unread Messages : 4
MESSAGE #1:
FROM: Mayur Bhindi <mayursoni0902@gmail.com>
TO: Mayur Bhindi <mayursoni0902@gmail.com>
Subject : null
Received Date : Mon Apr 15 00:19:27 IST 2013
Content : javax.mail.internet.MimeMultipart@18825b3
Content Type : multipart/ALTERNATIVE; boundary=047d7b6dd07882249904da56986c
Message : 
www.google.com
Message : 
<div dir="ltr"><a href="http://www.google.com">www.google.com</a><br></div>

MESSAGE #2:
FROM: Mayur Bhindi <mayursoni0902@gmail.com>
TO: Mayur Bhindi <mayursoni0902@gmail.com>
Subject : null
Received Date : Mon Apr 15 03:33:01 IST 2013
Content : javax.mail.internet.MimeMultipart@e5bbd6
Content Type : multipart/ALTERNATIVE; boundary=047d7b6da180bb8c2a04da594cde
Message : 
Win Cash
Message : 
Win Cash<br>

MESSAGE #3:
FROM: Mayur Bhindi <mayursoni0902@gmail.com>
TO: Mayur Bhindi <mayursoni0902@gmail.com>
Subject : null
Received Date : Mon Apr 15 03:38:24 IST 2013
Content : javax.mail.internet.MimeMultipart@1d62270
Content Type : multipart/ALTERNATIVE; boundary=047d7b5d8ea104216c04da5960c4
Message : 
Win cash
Message : 
Win cash<br>

MESSAGE #4:
FROM: Mayur Bhindi <mayursoni0902@gmail.com>
TO: mayursoni0902 <mayursoni0902@gmail.com>
Subject : cash
Received Date : Mon Apr 15 03:47:25 IST 2013
Content : Win

Content Type : TEXT/PLAIN; charset=ISO-8859-1
Exception arise at get Content
java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.Multipart
        at desktopapplication3.DesktopApplication3View.getContent1(DesktopApplication3View.java:179)
        at desktopapplication3.DesktopApplication3View.printEnvelope(DesktopApplication3View.java:132)
        at desktopapplication3.DesktopApplication3View.printAllMessages(DesktopApplication3View.java:103)
        at desktopapplication3.DesktopApplication3View.Mailsender(DesktopApplication3View.java:76)
        at desktopapplication3.DesktopApplication3View.jButton1ActionPerformed(DesktopApplication3View.java:433)
        at desktopapplication3.DesktopApplication3View.access$800(DesktopApplication3View.java:39)
        at desktopapplication3.DesktopApplication3View$4.actionPerformed(DesktopApplication3View.java:328)
        at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
        at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
        at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
        at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
        at java.awt.Component.processMouseEvent(Component.java:6038)
        at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
        at java.awt.Component.processEvent(Component.java:5803)
        at java.awt.Container.processEvent(Container.java:2058)
        at java.awt.Component.dispatchEventImpl(Component.java:4410)
        at java.awt.Container.dispatchEventImpl(Container.java:2116)
        at java.awt.Component.dispatchEvent(Component.java:4240)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
        at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
        at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
        at java.awt.Container.dispatchEventImpl(Container.java:2102)
        at java.awt.Window.dispatchEventImpl(Window.java:2429)
        at java.awt.Component.dispatchEvent(Component.java:4240)
        at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
        at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
        at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
        at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

Win

BUILD STOPPED (total time: 40 seconds)

please let me know as soon as possible.

Thanks..

Clearly , you are trying to assign the Multipart object to String referrence and that is why you are getting that ClassCastException

so how can i cast that multipart message into string...
means how can i convert message body into string....

Thanks

How can i bind jProgressBar to progress of fetching mails of INBOX using java mail API,means i am fetching mails and that progress of process bind to jProgressBar.

Chetan: Welcome to DaniWeb
Our Site Rules (which you agreed to when you signed up) include:
"Do not hijack old threads by posting a new question as a reply to an old one"
http://www.daniweb.com/community/rules

Please start your own new thread for your question

There is a problem with mail.jar for Java. I have the same problem and I found solution, for android you need different mail.jar. You can read it all on this link.

Hi milil.
1. This thread is 9 months old
2. It isn't about android Java

Your posts are welcome, but please ensure they are relevant and timely.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.