Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Application reading a Gmail message with Javamail?

  1. #1
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Application reading a Gmail message with Javamail?

    Greetings, and thank you for stopping by!

    I'm working on a application in Java which needs to be able to send and retrieve Gmails, and depending on the received information possibly store some of it. It can already send Gmails properly, and I've been able to make the program look for undread Gmails and start reading them. I can read stuff like the subject, the date it was sent and retrieved, who sent it and the like, but for some reason retrieving the actual information within the Gmail seems to be really difficult.

    This is the current code I'm using to retrieve a Gmail:

    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.Reader;
    import java.io.StringWriter;
    import java.util.*;
     
    import javax.mail.*;
    import javax.mail.search.FlagTerm;
    import javax.swing.JOptionPane;
     
    import org.apache.poi.util.IOUtils;
     
    @SuppressWarnings("unused")
    public class MailRetrieveMail {
     
     
     
     
    	public void retrieveMail()
    	{
     
    		Properties props = System.getProperties();
    		props.setProperty("mail.store.protocol", "imaps");
    		try 
    		{
    		  Session session = Session.getDefaultInstance(props, null);
    		  Store store = session.getStore("imaps");
    		  store.connect("imap.gmail.com", "SomeMail@gmail.com", "somePassword");
    		  Folder inbox = store.getFolder("Inbox");
     
    		  inbox.open(Folder.READ_ONLY);
    		  Message messages[] = inbox.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
     
    		  JOptionPane.showMessageDialog(null, "Number of undread messages: " + messages.length);
     
    		  FetchProfile fetchProfile = new FetchProfile();
     
    		  fetchProfile.add(FetchProfile.Item.ENVELOPE);
    		  fetchProfile.add(FetchProfile.Item.CONTENT_INFO);
     
    		  inbox.fetch(messages, fetchProfile);
     
    		  try
    		  {
    			printAllMessages(messages);
     
    			inbox.close(true);
    			store.close();
     
    		  }catch(Exception ex)
    		  {
    			  JOptionPane.showMessageDialog(null, "Exception when reading email.");
    			  ex.printStackTrace();
    		  }
     
    		} catch (NoSuchProviderException e) 
    		{
    		  e.printStackTrace();
    		  System.exit(1);
    		} catch (MessagingException e) 
    		{
    		  e.printStackTrace();
    		  System.exit(2);
    		}
    	}
     
     
        public void printAllMessages(Message[] messages) throws Exception
     
        {
     
            for (int i = 0; i < messages.length; i++)
            {
     
                JOptionPane.showMessageDialog(null, "MESSAGE #" + (i + 1) + ":");
     
                printEnvelope(messages[i]);
            }
        }
     
     
        public void printEnvelope(Message message) throws Exception
     
        {
     
            Address[] a;
     
     
            if ((a = message.getFrom()) != null) {
                for (int j = 0; j < a.length; j++) {
                }
            }
            if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
                for (int j = 0; j < a.length; j++) {
                }
            }
            String subject = message.getSubject();
            String content = message.getContent().toString();
     
            Date receivedDate = message.getReceivedDate();
     
     
            System.out.println("Subject: " + subject);
            JOptionPane.showMessageDialog(null, "Subject: " + subject);
            if (receivedDate != null) {
    //        	JOptionPane.showMessageDialog(null, "Received Date: " + receivedDate.toString());
            }
    //        JOptionPane.showMessageDialog(null, "Sent Date: " + sentDate.toString());
     
            getContent(message);
     
        }
     
        public void getContent(Message msg)
     
        {
            try {
    //            String contentType = msg.getContentType();
    //            JOptionPane.showMessageDialog(null, "Content Type : " + contentType);
                Multipart mp = (Multipart) msg.getContent();
                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 inputStream = p.getInputStream();
            // If "is" is not already buffered, wrap a BufferedInputStream
            // around it.
            if (!(inputStream instanceof BufferedInputStream)) {
            	inputStream = new BufferedInputStream(inputStream);
            }
            int c;
            String k = "";
     
            byte bg[];
    //        JOptionPane.showMessageDialog(null, "Message : ");
            while ((c = inputStream.read()) != -1) {
                System.out.write(c);
     
            }
     
     
     
     
            String inputStreamString = readFully(inputStream, "UTF-8");
     
     
     
            JOptionPane.showMessageDialog(null, "inputStream: " + inputStreamString);
     
    //        BufferedReader bufferRead = new BufferedReader(new Reader(System.out));
    //	    String s = bufferRead.readLine();
     
    //        JOptionPane.showMessageDialog(null, "s: " + s);
     
        }
     
    	public String readFully(InputStream inputStream, String encoding)
    	        throws IOException {
    	    return new String(readFully(inputStream), encoding);
    	}    
     
    	private byte[] readFully(InputStream inputStream)
    	        throws IOException {
    	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	    byte[] buffer = new byte[1024];
    	    int length = 0;
    	    while ((length = inputStream.read(buffer)) != -1) {
    	        baos.write(buffer, 0, length);
    	    }
    	    return baos.toByteArray();
    	}
     
    }

    Now somehow this part works and prints out the correct value into the console:

            int c;
            while ((c = inputStream.read()) != -1) {
                System.out.write(c);
     
            }

    But I can't for the mind of me figure out how to convert it to a readable String that I can actually use.


    This part:

            String inputStreamString = readFully(inputStream, "UTF-8");
     
     
     
            JOptionPane.showMessageDialog(null, "inputStream: " + inputStreamString);
     
     
     
        }
     
    	public String readFully(InputStream inputStream, String encoding)
    	        throws IOException {
    	    return new String(readFully(inputStream), encoding);
    	}    
     
    	private byte[] readFully(InputStream inputStream)
    	        throws IOException {
    	    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	    byte[] buffer = new byte[1024];
    	    int length = 0;
    	    while ((length = inputStream.read(buffer)) != -1) {
    	        baos.write(buffer, 0, length);
    	    }
    	    return baos.toByteArray();
    	}

    Is just another failed attempt, it too just prints it to the console and doesn't return any visible value at all that I can use. It also doesn't filter out all the non-interesting stuff unlike the example above it.

    I've searched around a lot and seen lots of solutions presented, but either I didn't get them to work or they simply printed it to the console, I'm sure this is a fairly easy thing to and probably often asked but, I'm stuck all the same.

    Any help would be greatly appreciated! =)


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,104
    Thanks
    52
    Thanked 2,285 Times in 2,256 Posts

    Default Re: Application reading a Gmail message with Javamail?

    The String class has a constructor that will create a String from a byte array.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Oct 2013
    Posts
    78
    Thanks
    55
    Thanked 0 Times in 0 Posts

    Default Re: Application reading a Gmail message with Javamail?

    I'm afraid I don't quite follow what you mean, but I fooled around a bit with it using a byte array and I think I got the result I needed:

            InputStream inputStream = p.getInputStream();
            if (!(inputStream instanceof BufferedInputStream)) {
            	inputStream = new BufferedInputStream(inputStream);
            }
            int c;
     
            byte[] byteArray = new byte[90000000];
            int byteCounter = 0;
            while ((c = inputStream.read()) != -1) {
                System.out.write(c);
                byteArray[byteCounter] = (byte) c;
                byteCounter++;
            }
     
            byte[] realByteArray = new byte[byteCounter];
            for(int i = 0; i < byteCounter; i++)
            {
            	realByteArray[i] = byteArray[i];
            }
     
            String message = new String(realByteArray);
     
            JOptionPane.showMessageDialog(null, "...: " + message);
            byteCounter = 0;

    Does this look like an ok way to go, or is there a better way of doing it?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,104
    Thanks
    52
    Thanked 2,285 Times in 2,256 Posts

    Default Re: Application reading a Gmail message with Javamail?

    The constructor has parameters for indexing into the array so you wouldn't need to do a copy.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    Feb 2014
    Posts
    180
    Thanks
    0
    Thanked 48 Times in 45 Posts

    Default Re: Application reading a Gmail message with Javamail?

    Your code doesn't seem to handle the various possible message content types. I'd say the first thing to do would be to do away with the JOptionPane.showMessageDialog calls as they get in the way of displaying the output, and just use printlns.

    Study the example at JavaMail API Fetching Emails. The key method in the example is the writePart(Part p) method that treats the Message object as a Part type that can contain further Parts (e.g., in the case of a multipart message.) Always test the Part's MIME type (using isMimeType()), and in the case of a multipart, recursively call the writePart method, which in turn will further test the part's MIME type for proper handling.

Similar Threads

  1. Reading from Microsoft Message Queue (MSMQ)
    By arunjavaforum in forum Java Theory & Questions
    Replies: 0
    Last Post: March 22nd, 2012, 03:07 AM
  2. Reading from another java application
    By xAndrewx in forum Java Theory & Questions
    Replies: 1
    Last Post: January 2nd, 2012, 03:15 AM
  3. Replies: 2
    Last Post: March 23rd, 2011, 08:51 AM
  4. Replies: 2
    Last Post: March 3rd, 2011, 01:22 PM
  5. JavaMail and Gmail
    By khushbu in forum Java Servlet
    Replies: 2
    Last Post: May 21st, 2010, 01:11 AM