I am trying to send email to user provided email id and I am getting below :
org.springframework.mail.MailSendException:
Failed messages: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException
Now the problem is I can catch MailSendException and send a Meaningful error message to Client saying, please provide valid emailId, but MailSendException is a very generic exception to catch and catching it doesn't guarantee that the exception has occurred because of invalid email id. This exception can occur for various other reasons.
My Problem is that I want to catch SMTPAddressFailedException but unfortunately in this case it is a nested exception and the actual exception thrown by Spring is a very generic MailSendException. Please suggest
I figured it out this way. The Spring's MailSendException has getMessageExceptions()
which will contain all the nested root exception. This was my requirement as I wanted to find out whether the nested root exception is SMTPAddressFailedException or not. Turns out the nested exception I got from getMessageExceptions()
was javax mail SendFailedException
so I had to use that SendFailedException
getNextException() to find out the nested root exception. A little lengthy but totally worth it to find out exact nested root exception:
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;
}
}
}