Rishi Rdy
Rishi Rdy

Reputation: 215

How to fix javax.mail.AuthenticationFailedException Invalid credentials

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

Upvotes: 15

Views: 16344

Answers (2)

Nandan
Nandan

Reputation: 557

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

Upvotes: 3

TechFree
TechFree

Reputation: 2954

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

Upvotes: 20

Related Questions