public void postMail(String recipients[], String subject, String message, String from) throws MessagingException
{
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", this.smtpHostName);
props.put("mail.smtp.port", this.smtpPort);
props.put("mail.smtp.auth", "false");
props.put("mail.smtp.connectiontimeout", this.connectionTimeout);
props.put("mail.smtp.timeout", this.socketIOTimeout);
//创建Session实例对象
Session session = Session.getDefaultInstance(props, null);
session.setDebug(false);
//创建MimeMessage实例对象
Message msg = new MimeMessage(session);
InternetAddress addressFrom = new InternetAddress(from);
//设置发件人地址
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
{
addressTo[i] = new InternetAddress(recipients[i]);
}
//设置收件人地址
msg.setRecipients(Message.RecipientType.TO, addressTo);
//设置邮件主题
msg.setSubject(subject);
//设置message为邮件正文,指定MINI类型为text/plain类型,并制定字符编码为KSC5601
msg.setContent(message, "text/plain;charset=KSC5601");
//发送邮件
try {
Transport.send(msg);
}catch(SendFailedException e) {
// 打印无效地址
Address[] invalid = e.getInvalidAddresses();
if (invalid != null) {
System.out.println("unsend mail: invalid address");
for (int i = 0; i < invalid.length; i++) {
System.out.println("invalid address:" + invalid[i]);
}
}
// 重新组装邮箱地址
Address[] validAddresses = e.getValidUnsentAddresses();
if (validAddresses != null) {
String[] toUsers = new String[validAddresses.length];
for (int i = 0; i < validAddresses.length; i++) {
toUsers[i] = validAddresses[i].toString();
}
postMail(toUsers, subject, message, from);
}
}
catch (MessagingException me) {
me.printStackTrace();
System.out.println(me.getMessage());
}
}
需要在catch里捕获发送失败的异常,SendFailedException,该异常类会获取有效地址和无效地址,将有效地址重新发送就可以,通过递归可实现过滤无效地址