I am trying since few days to retrieve email being sent using javax mail api. Dependency used -
<artifactId>javax.mail</artifactId>
I am getting error messages like cannot connect to store or connection time out when it tries to connect to store. Here is my code
public static void main(String[] args) throws IOException {
String userName = "mncjhc@gmail.com";
String password = "ckjbc";
String subjectKeyword = "New Registration – Successful";
String fromEmail = "djhgdd@gmail.com";
String bodySearchText = "You have successfully register to our services";
searchEmail(userName, password, subjectKeyword, fromEmail, bodySearchText);
}
public static void searchEmail(String userName, String password, final String subjectKeyword, final String fromEmail, final String bodySearchText) throws IOException {
Properties properties = new Properties();
boolean val = false;
// server setting
properties.put("mail.store.protocol", "imap");
properties.put("mail.imap.host", "imap.gmail.com");
properties.put("mail.imap.port", 143);
// SSL setting
properties.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.imap.ssl.enable", "true");
properties.setProperty("mail.imap.socketFactory.fallback", "false");
properties.setProperty("mail.imap.socketFactory.port", String.valueOf(143));
properties.put("mail.imaps.ssl.checkserveridentity", "false");
properties.put("mail.imaps.ssl.trust", "*");
properties.put("mail.imap.fetchsize", "519200");
properties.put("mail.imaps.connectiontimeout", 1000);
properties.put("mail.imaps.connectionpooltimeout", 1000);
properties.put("mail.imaps.onTimeout", 1000);
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
userName, password);// Specify the Username and the PassWord
}
});
try {
// connects to the message store
Store store = session.getStore("imap");
store.connect("imap.gmail.com", Integer.parseInt("143"), userName, password);
System.out.println("Connected to Email server….");
// opens the inbox folder
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
folderInbox.close(false);
store.close();
}
}