Showing posts with label Programmatically folder in imap.. Show all posts
Showing posts with label Programmatically folder in imap.. Show all posts

Friday, 27 September 2013

Access GMail with imap using java mail api

 

I had to search through quite a few web pages for this. So I am putting it here for future reference. My conscience pricks for putting all the code in main method. But I guess this is an exception.  :)

import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
public class InboxReader {
public static void main(String args[]) {
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", "<username>", "password");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}
}
}



Use the code below to get the available gmail folders for your account
 
Folder[] folder = store.getDefaultFolder().list();

// get the array folders in server
int i=0;
for( i=0;i<folder.length;i++)
System.out.println("Press "+i
 +" to read "+folder[i].getName()+" folder");
int choice=in.nextInt(); 
// getName() method returns the name of folder