我正在尝试使用 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
我应该做什么?
最佳答案
将连接代码放入 try-catch
block 中并捕获 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");
}
编辑:您收到错误:异常AuthenticationFailedException已被捕获
的原因是因为AuthenticationFailedException
是MessagingException的子级
你已经捕获了,看看当你改变异常的顺序时会发生什么,即在 MessagingException
AuthenticationException
关于java - 如何检查用户提供的邮箱地址和密码是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24198163/