Displaying emails in a JTable (Java Swing)

Posted by Paul on Stack Overflow See other posts from Stack Overflow or by Paul
Published on 2010-05-15T17:53:39Z Indexed on 2010/05/15 17:54 UTC
Read the original article Hit count: 315

Filed under:
|
|
|

Hi I'm new to all this. I have been trying to display fetched emails in a JTable using the JavaMail add-on. However when I ask the program to set the value it never does. I have been working in NetBeans if that is any help? the fetchMail class finds all may on a server. The gui class is used to display all emails in a table as well as creating mail.

You will probably think that I have tried it like a bull in a china shop, I am new to Java and trying to give myself a challenge. Any help/advice would be greatly appreciated

fetchMail:

package mail;

import java.util.; import java.io.; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.mail.; import javax.mail.internet.; import javax.mail.search.; import javax.activation.;

public class fetchMail {

public void fetch(String username, String pass, String search){
    MessagesTableModel tableModel = new MessagesTableModel();
    String complete;
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
    gui gui = new gui();
    // SUBSTITUTE YOUR ISP's POP3 SERVER HERE!!!
    String host = "imap.gmail.com";
    // SUBSTITUTE YOUR USERNAME AND PASSWORD TO ACCESS E-MAIL HERE!!!
    String user = username;
    String password = pass;
    // SUBSTITUTE YOUR SUBJECT SUBSTRING TO SEARCH HERE!!!
    String subjectSubstringToSearch = search;

    // Get a session.  Use a blank Properties object.
    Session session = Session.getInstance(new Properties());
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.setProperty("mail.imap.socketFactory.fallback", "false");
    try {

        // Get a Store object
        Store store = session.getStore("imaps");
        store.connect(host, user, password);

        // Get "INBOX"
        Folder fldr = store.getFolder("INBOX");
        fldr.open(Folder.READ_WRITE);
        int count = fldr.getMessageCount();
        System.out.println(count  + " total messages");


        // Message numebers start at 1
        for(int i = 1; i <= count; i++) {
                                // Get  a message by its sequence number
            Message  m = fldr.getMessage(i);

            // Get some headers
            Date date = m.getSentDate();
            int pos = i - 1;
            String d = df.format(date);
            Address [] from = m.getFrom();
            String subj = m.getSubject();
            String mimeType = m.getContentType();
            complete = date + "\t" + from[0] + "\t" +
                                subj + "\t" + mimeType;
            //tableModel.setMessages(m);
            gui.setDate(d, pos);

           // System.out.println(d + " " + i);

        }



        // Search for e-mails by some subject substring
        String pattern = subjectSubstringToSearch;
        SubjectTerm st = new SubjectTerm(pattern);
        // Get some message references
        Message [] found = fldr.search(st);

        System.out.println(found.length +
                            " messages matched Subject pattern \"" +
                            pattern + "\"");

        for (int i = 0; i < found.length; i++) {
            Message m = found[i];
            // Get some headers
            Date date = m.getSentDate();
            Address [] from = m.getFrom();
            String subj = m.getSubject();
            String mimeType = m.getContentType();
            //System.out.println(date + "\t" + from[0] + "\t" +
            //                    subj + "\t" + mimeType);

            Object o = m.getContent();
            if (o instanceof String) {
              //  System.out.println("**This is a String Message**");
               // System.out.println((String)o);
            }
            else if (o instanceof Multipart) {
              //  System.out.print("**This is a Multipart Message.  ");
                Multipart mp = (Multipart)o;
                int count3 = mp.getCount();
               // System.out.println("It has " + count3 +
                //    " BodyParts in it**");
                for (int j = 0; j < count3; j++) {
                    // Part are numbered starting at 0
                    BodyPart b = mp.getBodyPart(j);
                    String mimeType2 = b.getContentType();
                 //   System.out.println( "BodyPart " + (j + 1) +
                 //                       " is of MimeType " + mimeType);

                    Object o2 = b.getContent();
                    if (o2 instanceof String) {
                 //       System.out.println("**This is a String BodyPart**");
                     //   System.out.println((String)o2);
                    }
                    else if (o2 instanceof Multipart) {
                //        System.out.print(
                  //          "**This BodyPart is a nested Multipart.  ");
                        Multipart mp2 = (Multipart)o2;
                        int count2 = mp2.getCount();
                //        System.out.println("It has " + count2 +
                //            "further BodyParts in it**");
                    }
                    else if (o2 instanceof InputStream) {
                //        System.out.println(
               //             "**This is an InputStream BodyPart**");
                    }
                } //End of for
            }
            else if (o instanceof InputStream) {
            //    System.out.println("**This is an InputStream message**");
                InputStream is = (InputStream)o;
                // Assumes character content (not binary images)
                int c;
                while ((c = is.read()) != -1) {
             //       System.out.write(c);
                }
            }

            // Uncomment to set "delete" flag on the message
            //m.setFlag(Flags.Flag.DELETED,true);

        } //End of for

        // "true" actually deletes flagged messages from folder
        fldr.close(true);
        store.close();

    }
    catch (MessagingException mex) {
        // Prints all nested (chained) exceptions as well
        mex.printStackTrace();
    }
    catch (IOException ioex) {
        ioex.printStackTrace();
    }

}

}

gui:

/* * gui.java * * Created on 13-May-2010, 18:29:30 */

package mail;

import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Vector; import javax.mail.Address; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel;

public class gui extends javax.swing.JFrame { private MessagesTableModel tableModel;

// Table listing messages.
private JTable table;
String date;



/** Creates new form gui */
public gui() {


    initComponents();
}




@SuppressWarnings("unchecked")

private void initComponents() {

    recieve = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    inboxTable = new javax.swing.JTable();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    recieve.setText("Receve");
    recieve.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            recieveActionPerformed(evt);
        }
    });

    jButton1.setText("new");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    inboxTable.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null},
            {null, null, null},
            {null, null, null},
            {null, null, null}
        },
        new String [] {
            "Date", "subject", "sender"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.String.class, java.lang.String.class, java.lang.String.class
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }
    });
    jScrollPane1.setViewportView(inboxTable);
    inboxTable.getColumnModel().getColumn(0).setResizable(false);
    inboxTable.getColumnModel().getColumn(1).setResizable(false);
    inboxTable.getColumnModel().getColumn(2).setResizable(false);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(39, 39, 39)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 558, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(recieve)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(73, 73, 73))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(31, 31, 31)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(recieve)
                .addComponent(jButton1))
            .addGap(18, 18, 18)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(179, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>



private void recieveActionPerformed(java.awt.event.ActionEvent evt) {
    fetchMail fetch = new fetchMail();
    fetch.fetch(email goes here, password goes here, search goes here);


}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    createMail create = new createMail();
   centerW center = new centerW();
   //create.attVis();
   center.center(create);
   create.setVisible(true);
}


    public void setDate(String Date, int pos){

        //pos = pos + 1;

     String [] s = new String [5];
     s[pos] = Date;

    inboxTable.setValueAt(Date, pos, 0);
    }
    public String getDate(){
        return date;
    }









/**
* @param args the command line arguments
*/
public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new gui().setVisible(true);

        }
    });
}

// Variables declaration - do not modify
private javax.swing.JTable inboxTable;
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton recieve;
// End of variables declaration

}

© Stack Overflow or respective owner

Related posts about java

Related posts about email-client