如何通过两步验证访问Gmail?

tro*_*yen 6 java email imap

最近我在我的Gmail帐户中设置了两步验证,我尝试使用Java Mail API连接到我的gmail帐户,但它没有连接.

我的代码:

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", "my_account@gmail.com", "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);
    }
Run Code Online (Sandbox Code Playgroud)

我从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)
Run Code Online (Sandbox Code Playgroud)

请问有什么方法可以解决这个问题.

提前致谢.

Hem*_*nth 6

激活gmail帐户的两步验证后,使用您的gmail凭据登录以下链接并生成应用程序专用密码(ASP).您可以在代码中使用生成的密码.只需添加ASP代替普通密码即可.它应该工作.

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

更新:2018年7月30日

当您打开此链接并手动使用gmail ID和密码登录一次时,您将看到如下所示的页面.在第一个下拉列表中选择"邮件"选项

在此输入图像描述

在第二个下拉列表中,根据您的要求选择平台,说"Windows计算机"或"Mac"

在此输入图像描述

然后,单击生成按钮,您将在下一个屏幕中看到包含16个字母的代码.

在这样的java邮件程序中使用此密码作为密码

store.connect("imap.gmail.com", "gmail id used in the previous step", "16 alphabets code");
Run Code Online (Sandbox Code Playgroud)