Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting mail from GMail into Java application using IMAP

I want to access messages in Gmail from a Java application using JavaMail and IMAP. Why am I getting a SocketTimeoutException ?

Here is my code:

Properties props = System.getProperties(); props.setProperty("mail.imap.host", "imap.gmail.com"); props.setProperty("mail.imap.port", "993"); props.setProperty("mail.imap.connectiontimeout", "5000"); props.setProperty("mail.imap.timeout", "5000");  try {     Session session = Session.getDefaultInstance(props, new MyAuthenticator());     URLName urlName = new URLName("imap://[email protected]:[email protected]");     Store store = session.getStore(urlName);     if (!store.isConnected()) {         store.connect();     } } catch (NoSuchProviderException e) {     e.printStackTrace();     System.exit(1); } catch (MessagingException e) {     e.printStackTrace();     System.exit(2); } 

I have set the timeout values so that it wouldn't take "forever" to timeout. Also, MyAuthenticator also has the username and password, which seems redundant with the URL. Is there another way to specify the protocol? (I didn't see it in the JavaDoc for IMAP.)

like image 402
Dave Avatar asked Sep 14 '08 07:09

Dave


People also ask

Can you access Gmail via IMAP?

Gmail provides IMAP access to your Gmail account, so you can connect to your email from mobile devices and desktop email clients.


1 Answers

Using imaps was a great suggestion. Neither of the answers provided just worked for me, so I googled some more and found something that worked. Here's how my code looks now.

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>@gmail.com", "<password>");   ... } catch (NoSuchProviderException e) {   e.printStackTrace();   System.exit(1); } catch (MessagingException e) {   e.printStackTrace();   System.exit(2); } 

This is nice because it takes the redundant Authenticator out of the picture. I'm glad this worked because the SSLNOTES.txt make my head spin.

like image 190
Dave Avatar answered Sep 24 '22 02:09

Dave