我怎样才能抓住AuthenticationFailedExceptions?
我基本上有一个登录屏幕,我从用户名获取文本,从密码获取文本。我正在使用Gmail身份验证。
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host","smtp.gmail.com");
properties.put("mail.smtp.port","587");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
);
如何检查身份验证是否成功?我知道当调用像Transport.send(message)
这样的语句时会出现错误。但是我想检查身份验证是否成功--实际上并不是发送消息。谢谢!
发布于 2014-08-25 22:13:56
Transport transport;
try {
transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", username, password);
transport.close();
//Authentication success
} catch (AuthenticationException e) {
System.out.println("Authentication Exception");
//Authentication failed. Handle this here.
}
这部分代码在OP中的原始代码部分之后,将能够进行验证,前提是用户名和密码已经定义。
如果执行catch语句,身份验证失败。如果没有,身份验证就成功了。
发布于 2014-08-25 22:05:59
每当您试图发送带有错误凭据的邮件时,它都会抛出
javax.mail.AuthenticationFailedException So, you can catch that exception in catch block to resolve your problem
见docs:[http://docs.oracle.com/javaee/1.4/api/javax/mail/AuthenticationFailedException.html]
try
{
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
);
}
catch(AuthenticationFailedException e)
{
// your action
}
https://stackoverflow.com/questions/25498542
复制