Getting mail from GMail into Java application using IMAP

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.

Leave a Comment