Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access gmail with 2-step verification?

Tags:

java

email

imap

Recently I set up 2-step verification in my gmail account , and I try to connect to my gmail account using Java Mail API, but it didn't connect.

My code:

Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", "[email protected]", "password");
        System.out.println(store);

        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        Message messages[] = inbox.getMessages();
        for (Message message : messages) {
            System.out.println(message);
        }
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        System.exit(1);
    } catch (MessagingException e) {
        e.printStackTrace();
        System.exit(2);
    }

And what i get from logcat:

javax.mail.AuthenticationFailedException: [ALERT] Application-specific password required: http://support.google.com/accounts/bin/answer.py?answer=185833 (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:660)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)

What is the method to overcome this issue, please.

Thanks in advance.

like image 314
trongnguyen Avatar asked May 17 '13 04:05

trongnguyen


People also ask

Can you bypass Gmail 2-Step verification?

In order to bypass Google 2-step verification during setup, you'll need to do the following: Navigate to Settings > General Settings > Reset. Follow the setup process until you get to Connect to the WiFi Network. Tap the WiFi password textbox.


1 Answers

When you have activated 2-step verification for gmail account, login to the below link using your gmail credentials and generate application specific password (ASP). You can use the generated password in your code. Simply add the ASP in place of the normal password. It should work.

https://accounts.google.com/IssuedAuthSubTokens?hide_authsub=1

Update : 30-July 2018

When you open this link and login once with the gmail id and password manually, you will see this page as shown below. Select "Mail" option in the first drop down

enter image description here

In the second drop down, select the platform based on your requirement, Say "Windows Computer" or "Mac"

enter image description here

Then, Click the generate button and you will see a code with 16 alphabets in the next screen.

Use this as a password in your java mail program like this

store.connect("imap.gmail.com", "gmail id used in the previous step", "16 alphabets code");
like image 124
HemChe Avatar answered Oct 06 '22 01:10

HemChe