项目需要集成邮件发送,之前在.net下写过smtp的邮件发送,好像可以直接获取状态码。在网上找到的javamail发送例子中并未给出如何获取状态码。而且sendMessage方法直接是void没任何返回参数。
之后在查阅api时终于有所发现
When sending a message, detailed information on each address that fails is available in an SMTPAddressFailedException chained off the top level SendFailedException that is thrown. In addition, if the mail.smtp.reportsuccess property is set, anSMTPAddressSucceededException will be included in the list for each address that is successful. Note that this will cause a top level SendFailedException to be thrown even though the send was successful.
SMTPAddressFailedException 和SMTPAddressSucceededException 中就包含了状态码
来自:http://blog.csdn.net/mouhk/article/details/8244665
自己写的测试代码
package com.demo.mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPAddressFailedException;
public class TestSendMail {
public static void main(String[] args) {
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.port", 25);
props.put("mail.smtp.auth", false);
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]",
"$$$$");
}
};
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true");
props.put("mail.from", "[email protected]");
props.put("mail.smtp.reportsuccess", true);
Session session = Session.getInstance(props, auth);
session.setDebug(false);
try {
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, "[email protected]");
msg.setSubject("JavaMail hello world example");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport.send(msg);
} catch (SMTPAddressFailedException ex) {
// 250是发送OK的 捕获到250 Mail OK
// 550 User not found: [email protected] 550错误 只能获取到Invalid
// Addresses没有发现这个邮箱
System.out
.println("SMTPAddressFailedException---------------------------"
+ ex.getReturnCode());
System.out
.println("SMTPAddressFailedException---------------------------"
+ ex.getCause().getMessage());
} catch (MessagingException mex) {
System.out.println("MessagingException------" + mex.getMessage());
}
}
}