Java 如何使用Spring mail API捕获嵌套的SMTPAddressFailedException

Java 如何使用Spring mail API捕获嵌套的SMTPAddressFailedException,java,spring,jakarta-mail,nested-exceptions,Java,Spring,Jakarta Mail,Nested Exceptions,我正在尝试向用户提供的电子邮件id发送电子邮件,我得到以下信息: org.springframework.mail.MailSendException: Failed messages: javax.mail.SendFailedException: Invalid Addresses; nested exception is: com.sun.mail.smtp.SMTPAddressFailedException 现在的问题是,我可以捕获MailSendException并向客户端发送一

我正在尝试向用户提供的电子邮件id发送电子邮件,我得到以下信息:

org.springframework.mail.MailSendException: 
Failed messages: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException
现在的问题是,我可以捕获MailSendException并向客户端发送一条有意义的错误消息,告诉客户端,请提供有效的emailId,但MailSendException是一个非常通用的捕获异常,它不能保证异常是因为无效的email id而发生的。此异常可能是由于各种其他原因而发生的


我的问题是,我想捕获SMTPAddressFailedException,但不幸的是,在本例中,它是一个嵌套异常,Spring引发的实际异常是一个非常通用的MailSendException。请建议

看起来您可以通过MailSendException方法获得此详细信息。

我是这样想的。Spring的MailSendException具有
getMessageExceptions()
,它将包含所有嵌套的根异常。这是我的要求,因为我想知道嵌套的根异常是否为SMTPAddressFailedException。原来我从
getMessageException()
得到的嵌套异常是javax-mail
SendFailedException
,所以我必须使用该
SendFailedException
getNextException()来查找嵌套的根异常。有点长,但完全值得找出确切的嵌套根异常:

 catch (MailSendException e){
        logger.error("MailSendException found.",e);
        Exception[] exceptionArray = e.getMessageExceptions();
        e.getFailedMessages();
        boolean isSMTPAddressFailedException = false;
        for(Exception e1 : exceptionArray){
            if(e1 instanceof SendFailedException){
                Exception e2 = ((SendFailedException)e1).getNextException();
                if(e2 instanceof SMTPAddressFailedException){
                    logger.error("Caught SMTPAddressFailedException. Invalid email id of User/Dealer",e2);
                    utilityService.formatBasicResponseWithMessage(response, ResponseCodes.INVALID_EMAILID, serviceRequestVO.getLanguageId());
                    isSMTPAddressFailedException=true;
                    break;
                }
            }
        }

它在2021年3月也能工作吗(使用SpringBoot 2.4.3)?我试过了,但没有成功。!