12

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

Rishabh Deep Singh
  • 807
  • 1
  • 12
  • 24
Rishi Rdy
  • 185
  • 2
  • 2
  • 10
  • I disabled two way authentication also – Rishi Rdy Jun 10 '19 at 10:36
  • There could be chances that Gmail account's third party access security check is disabled. – AJ. Jun 10 '19 at 10:59
  • I have enabled less secure app and now I got Username and password not accepted. – Rishi Rdy Jun 10 '19 at 11:09
  • There are lots of solution for your error ... check this ..https://www.digitalocean.com/community/questions/unable-to-send-mail-through-smtp-gmail-com – AJ. Jun 10 '19 at 11:12
  • https://answers.microsoft.com/en-us/windowslive/forum/all/username-and-password-not-accepted-by-popgmailcom/c61c8736-e91c-4262-a004-96ae7c3639a0 – AJ. Jun 10 '19 at 11:15
  • for solve this problem you welcome read my answer here https://stackoverflow.com/a/72592946/2347210 – Vladi Jul 25 '22 at 08:25

2 Answers2

19

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

TechFree
  • 2,600
  • 1
  • 17
  • 18
2

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

Nandan
  • 497
  • 2
  • 7
  • 18