java smtp怎么开启_如何使用JavaMail获取SMTP服务器响应?

我正在使用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响应?

解决方法:

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

/**

* Should we report even successful sends by throwing an exception?

* If so, a SendFailedException 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());

}

}

标签:java,smtp,javamail,response

来源: https://codeday.me/bug/20190625/1283624.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值