问题
发送邮件时,地址中如果包含一个无效的邮件地址(地址是合法的,但该邮件地址不存在,比如说人员离职导致的邮件地址不存在),就会得到如下错误,从而导致整个发送失败。
org.springframework.mail.MailSendException: Failed messages: javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 Mailbox not found or access denied at
org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:490) at
org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:360) at
org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:355) at
问题解决
很多时候我们希望发送邮件时即使发送列表中存在无效的邮件地址,但其他的有效邮件地址能够被正常投递出去。
public class MailSendHelper {
/**
* 邮件发送
* @param mailTos 接收人
* @param mailCcs 抄送人
* @param subject 主题
* @param content 内容
* @param personal 显示名称
* @param attachments 附件
* @param user 发件人
* @param pwd 密码
* @return
*/
public static MailSendStatus sendEmail(List<String> mailTos, List<String> mailCcs, String subject, String content,
String personal, List<File> attachments, String user, String pwd) {
if (StringUtils.isEmpty(content)) {
return MailSendStatus.CONTENT_EMPTY;
}
if (StringUtils.isEmpty(user) || StringUtils.isEmpty(pwd)) {
return MailSendStatus.USER_OR_PWD_EMPTY;
}
String[] to = parseAddr(mailTos);
if (null == to) {
return MailSendStatus.RECEIVER_EMPTY;
}
// 邮件发送器参数设置
JavaMailSenderImpl senderParam = new JavaMailSenderImpl();
senderParam.setHost("邮箱 smtp host 地址");
senderParam.setUsername(user);
senderParam.setPassword(pwd);
Properties javaMailProperties = new Properties();
javaMailProperties.put("mail.smtp.timeout", "超时时间");
javaMailProperties.put("mail.smtp.connectiontimeout", "链接超时时间");
senderParam.setJavaMailProperties(javaMailProperties);
try {
MimeMessageHelper helper = new MimeMessageHelper(senderParam.createMimeMessage(), true, "UTF-8");
// 邮件发送人
helper.setFrom(senderParam.getUsername(),
StringUtils.isEmpty(personal) ? "默认发件人显示名" : personal);
// 邮件接收人
helper.setTo(to);
// 抄送邮件
String[] cc = parseAddr(mailCcs);
if (null != cc) {
helper.setCc(cc);
}
// 邮件主题
helper.setSubject(StringUtils.isEmpty(subject) ? "默认主题名称" : subject);
// 邮件内容
helper.setText(buildContent(content), true);
// 添加附件
if (null != attachments && attachments.size() > 0) {
for(File file : attachments){
helper.addAttachment(MimeUtility.encodeText(file.getName()), file);
}
}
// 发送时间
helper.setSentDate(new Date());
// 邮件发送
Transport transport = helper.getMimeMessage().getSession().getTransport();
// 注册一个监听器,当有无效邮件地址异常时,我们将有效的且未发送的邮件地址重新投递
transport.addTransportListener(new TransportAdapter() {
@Override
public void messageNotDelivered(TransportEvent event) {
// 获取到有效的且未发送的邮件地址
Address[] validAddresses = event.getValidUnsentAddresses();
if (null == validAddresses || validAddresses.length == 0) {
return;
}
// 获取发送内容信息
Message message = event.getMessage();
try {
// 重新发送
transport.sendMessage(message, validAddresses);
} catch (Exception ex) {
log.error("mail send failed", ex);
}
}
});
transport.connect(senderParam.getHost(), senderParam.getUsername(), senderParam.getPassword());
transport.sendMessage(helper.getMimeMessage(), helper.getMimeMessage().getAllRecipients());
return MailSendStatus.SUCCESS;
} catch (SendFailedException ex) {
log.error("邮件发送地址无效: {}", Arrays.toString(ex.getInvalidAddresses()));
return MailSendStatus.PART_SUCCESS;
} catch (MessagingException ex) {
log.error("邮件发送初始化异常", ex);
} catch (UnsupportedEncodingException ex) {
log.error("邮件编码异常", ex);
} catch (Exception ex) {
log.error("邮件发送异常", ex);
}
return MailSendStatus.FAIL;
}
}
public enum MailSendStatus {
SUCCESS("发送成功"),
FAIL("发送失败"),
PART_SUCCESS("部分成功"),
CONTENT_EMPTY("邮件内容为空"),
RECEIVER_EMPTY("邮件接收人为空"),
USER_OR_PWD_EMPTY("用户名或密码为空")
;
@Getter
private String desc;
MailSendStatus(String desc) {
this.desc = desc;
}
}
原理
请打开 com.sun.mail.smtp.SMTPTransport#rcptTo() 方法
public class SMTPTransport extends Transport {
...
protected void rcptTo() throws MessagingException {
...
// try the addresses one at a time
for (int i = 0; i < addresses.length; i++) {
...
// check the server's response for address validity
// 如果是失效地址,retCode 为550
retCode = readServerResponse();
...
}
...
// copy the lists into appropriate arrays
// 将无效的邮件地址放入 Address[] validUnsentAddr 中
if (sendFailed) {
// copy invalid addrs
invalidAddr = new Address[invalid.size()];
invalid.toArray(invalidAddr);
// copy all valid addresses to validUnsent, since something failed
validUnsentAddr = new Address[valid.size() + validUnsent.size()];
int i = 0;
for (int j = 0; j < valid.size(); j++)
validUnsentAddr[i++] = (Address)valid.get(j);
for (int j = 0; j < validUnsent.size(); j++)
validUnsentAddr[i++] = (Address)validUnsent.get(j);
}
...
// 通知监听器
notifyTransportListeners(TransportEvent.MESSAGE_NOT_DELIVERED,
validSentAddr, validUnsentAddr,
invalidAddr, this.message);
...
}
...
}