gpt4 book ai didi

java - 如何使用 JavaMail 获取 SMTP 服务器响应?

转载 作者:搜寻专家 更新时间:2023-10-31 20:12:42 24 4
gpt4 key购买 nike

我正在使用 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 <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());
}
}

关于java - 如何使用 JavaMail 获取 SMTP 服务器响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17350438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com