如何检查用户提供的邮箱ID和密码是否正确?

时间:2014-06-13 05:15:36

标签: java email imap

我正在尝试验证用户使用imap java提供的电子邮件ID和密码。我已经编写了可以连接到帐户并下载邮件的基本代码。但是当电子邮件ID或密码不正确时,只会出现此错误:

avax.mail.AuthenticationFailedException: Invalid credentials wu2mb53991170pac
    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)
    at mailchecker.main(mailchecker.java:19)

但我想要的只是检查凭据是否正确。例如。如果凭据是正确的程序应打印好,否则对不起或类似的东西...我是新来的,所以任何想法我怎么能这样做?

修改 这是我的代码:

public static void main(String args[]) {
    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    try {
        System.out.println("hi");
        Session session = Session.getDefaultInstance(props, null);
        Store store = session.getStore("imaps");
        store.connect("imap.gmail.com", "<username>", "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.out.println("hi");
        System.exit(1);
    } catch (MessagingException e) {
        e.printStackTrace();
        System.exit(2);
    } catch (javax.mail.AuthenticationFailedException e) {
        e.printStackTrace();
        System.out.println("hi");
        System.exit(1);
    }
}

当我把它放错时。

error: exception AuthenticationFailedException has already been caught

我该怎么办?

1 个答案:

答案 0 :(得分:2)

将您的连接代码放在try-catch块中,然后抓住javax.mail.AuthenticationFailedException。例如:

try{
   //connect to mail server
    System.out.println("Ok");
}
catch(javax.mail.AuthenticationFailedException e)
{
    //display connection error to the user, maybe allow them to retry
    System.out.println("Sorry your credentials are incorrect");
}

编辑:收到error: exception AuthenticationFailedException has already been caught的原因是因为AuthenticationFailedException是您已经抓住的MessagingException的孩子,看看您更改时会发生什么异常的顺序,即在AuthenticationException

之前捕获MessagingException