Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix javax.mail.AuthenticationFailedException Invalid credentials

Tags:

java

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, "[email protected]", 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

like image 724
Rishi Rdy Avatar asked Jun 10 '19 10:06

Rishi Rdy


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

like image 83
TechFree Avatar answered Nov 04 '22 00:11

TechFree


Google no longer support 'Less Secure App Access'. Instead you need to enable 2- step verification on your google account and generate an app password to use with your mail application.

Use full links:

  1. 2- step verification
  2. Create and use app password

Gmail SMTP example

like image 1
Nandan Avatar answered Nov 03 '22 23:11

Nandan