5

我正在使用 JavaMail 1.5 发送邮件,并从我的测试中看到邮件发送成功。我SMTPTransport用来获取最后的服务器响应,但它是空的,与代码相同。getReportSuccess()返回false

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

尽管消息已成功发送,但收到此类响应的原因可能是什么?

有没有办法获得正确的 SMTP 响应?

4

1 回答 1

4

我不确定它是否完全涵盖了这个问题,但是当我浏览 SMTPTransport.java时,描述getReportSuccess()说:

/**
     * 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;
    }

所以,在我的代码中,为了确保发送过程已经成功完成,我setReportSuccess(true);在发送之前调用了然后处理了一个异常com.sun.mail.smtp.SMTPAddressSucceededException。以下代码片段适用于我:

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());
    }
}
于 2014-05-12T13:56:29.140 回答