How to fix javax.mail.AuthenticationFailedException Invalid credentials

Viewed 9635

Though I have used correct credentials I am unable to read emails using java

I have tried pop3 AND IMAP. All are displaying invalid credentials for all the EmailId's tried

Session session = Session.getDefaultInstance(new Properties( ));
Store store = session.getStore("imaps");
store.connect("imap.googlemail.com", 993, "example@gmail.com", password);
Folder inbox = store.getFolder( "INBOX" );
inbox.open( Folder.READ_ONLY );

// Fetch unseen messages from inbox folder
Message[] messages = inbox.search(
    new FlagTerm(new Flags(Flags.Flag.SEEN), false));

// Sort messages from recent to oldest
Arrays.sort( messages, ( m1, m2 ) -> {
  try {
    return m2.getSentDate().compareTo( m1.getSentDate() );
  } catch ( MessagingException e ) {
    throw new RuntimeException( e );
  }
} );

for ( Message message : messages ) {
  System.out.println( 
      "sendDate: " + message.getSentDate()
      + " subject:" + message.getSubject() );
}

I should be able to read email

2 Answers

The reason is that email box doesn't allow connections from less secure apps. Your code is fine.

Exception in thread "main" javax.mail.AuthenticationFailedException: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:474)
    at javax.mail.Service.connect(Service.java:275)

The above exception is thrown when less secure app access is tured OFF. Turn this ON to make the access available via program.

enter image description here

Related