How can I get SMTP server response using JavaMail?

I use JavaMail 1.5 to send mail and see in my tests that messages are sent successfully. I use SMTPTransport to get the response of the last server, but it is empty, the same as the 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 could be the reason for receiving such a response, although the message was sent successfully?

Is there a way to get the correct SMTP response?

+4
source share
1 answer

I'm not sure that it covers this question completely, but when I looked at SMTPTransport.java , the description of 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 make sure the transfer process completed successfully, I called setReportSuccess(true); before sending, and then handled the com.sun.mail.smtp.SMTPAddressSucceededException exception. The following code snippet works fine for me:

 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()); } } 
+4
source

Source: https://habr.com/ru/post/1488562/


All Articles