java.lang.reflect.InvocationTargetException on Login to Gmail using IMAP

446 views Asked by At

Here Im trying to login Gmail using IMAP(gmail API),but when passing Username & Password then im getting Invocation TargetException. Here is my code

`Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>@gmail.com", "<password>");
//Here im getting exception and below is the log
Exception in thread "main" javax.mail.AuthenticationFailedException: [ALERT] Please log in via your web browser: https://support.google.com/mail/accounts/answer/78754 (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:474)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
} 

Please help me how to resolve this.Thank You.

1

There are 1 answers

0
arnt On

You got an ALERT from gmail whose human-readable test suggests a particular URL. That's not really a suggestion or request, despite the word "please", it's a requirement.

If you want to log in, you have to carry out a web login first, and you have to use a browser that supports javascript and is capable of resolving a captcha.

There are ways to avoid this, usually. Either turn on OAUTH2 in the client code or change the security settings in the gmail account. Both usually work, but you have no guarantee. Google uses heuristics and assorted magic to guess whether you're the real user or an attacker, and if the assessment engine is too uncertain about a particular login, google wants to use two-factor authentication or a captcha.