Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get SMTP server response using JavaMail?

I'm using JavaMail 1.5 to send mail and see from my tests that messages are sent successfully. I use SMTPTransport to get last server response, but it's empty, same as code. getReportSuccess() returns false.

SMTPTransport t = (SMTPTransport)session.getTransport("smtps");
t.send(message);
String response = t.getLastServerResponse();
boolean s = t.getReportSuccess();
int code = t.getLastReturnCode();
return response;

What can be the reason of getting such response, though the message is sent successfully?

Is there any way to get correct SMTP response?

like image 455
GiorgosDev Avatar asked Oct 04 '22 16:10

GiorgosDev


1 Answers

I am not sure that it is completely cover this question, but as I glanced on SMTPTransport.java, the description to getReportSuccess() says:

/**
     * Should we report even successful sends by throwing an exception?
     * If so, a <code>SendFailedException</code> will always be thrown and
     * an {@link com.sun.mail.smtp.SMTPAddressSucceededException
     * SMTPAddressSucceededException} will be included in the exception
     * chain for each successful address, along with the usual
     * {@link com.sun.mail.smtp.SMTPAddressFailedException
     * SMTPAddressFailedException} for each unsuccessful address.
     *
     * @return  true if an exception will be thrown on successful sends.
     *
     * @since JavaMail 1.3.2
     */
    public synchronized boolean getReportSuccess() {
        return reportSuccess;
    }

So, in my code, to be made sure that sending proccess has been successfuly done, I invoked setReportSuccess(true); before sending and then handled an exception com.sun.mail.smtp.SMTPAddressSucceededException. The following code snippet works for me fine:

public synchronized void sendMail(String subject, String body, String user, String oauthToken, String recipients, String attachment)
{
    try {
        SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, user, oauthToken, true);
        MimeMessage message = new MimeMessage(session);

        /*Set whether successful sends should be reported by throwing
        **an exception.
        */
        smtpTransport.setReportSuccess(true);

        /**
        ***All actions to got the formated message
        **/

        /*Send message*/
        smtpTransport.sendMessage(message, message.getAllRecipients());
    } catch(android.os.NetworkOnMainThreadException e){
        Log.d("MY_LOG","NetworkOnMainThreadException");
    }
    catch(com.sun.mail.smtp.SMTPAddressSucceededException e){
        /**
        ***Message has been sent. Do what you need.
        **/         
    }
    catch (Exception e) {
        Log.d("MY_LOG", e.getMessage());
    }
}
like image 55
Sergey V. Avatar answered Oct 07 '22 19:10

Sergey V.