发送前的JavaMail密码验证

发送前的JavaMail密码验证,java,authentication,jakarta-mail,Java,Authentication,Jakarta Mail,如何捕获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

如何捕获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)
之类的语句时会出现错误。但我想检查身份验证是否成功,而不是实际发送消息。
谢谢

当您试图发送带有错误凭据的邮件时,它将抛出
javax.mail.AuthenticationFailedException 所以,您可以在catch块中捕获该异常以解决您的问题

见文件:[

假设定义了用户名和密码,那么在OP中原始代码部分之后的这段代码将能够进行验证


如果执行catch语句,则身份验证失败。如果未执行,则身份验证成功。

请尝试此@SunilSinghBora,谢谢您的链接。不过,我已经有了一个很好的紧凑解决方案。我将很快回答我自己的问题。不,这不起作用。不管怎样,都会创建会话。不会引发异常。只有当采取某种操作(如发送消息或建立连接)时抛出。我们不能在发送时捕获该异常吗,我是说在传输时?我们可以,但如果没有例外怎么办?如果用户输入了正确的密码和用户名怎么办。它会发送消息。我不传输。发送存在。它只是传输。发送(消息).
NoSuchProviderException
与身份验证无关。奇怪的是,有一个特定的例外,它的名称恰当,并在其他答案中提到-1@EJP所以你投了反对票?很有趣。考虑到这是正确的答案,正如我所证实的,OP。只要把那个挡块拿出来,它就会像预期的那样工作。我我不想发送电子邮件,只是验证身份验证。谢谢,请,希望下次在下一次投票之前做一些研究:)@EJP,这是我的问题,如果它解决了我的问题,我的答案是正确的。简单的说:)是的,我下一次投票,因为信息错误。第二个catch块将捕获AuthenticationException,因为它是ext结束MessaginException。它还将捕获与身份验证无关的所有其他异常。第一个catch块不会捕获任何身份验证异常,原因正如我所述。正确的解决方案是捕获AuthenticationException。
try
{
    Session session = Session.getInstance(properties, 
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                }
        );
}
catch(AuthenticationFailedException e)
{
    // your action
}
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.
}