PME-Blog

自由撰写
难得自在

Java邮件发送一个收件人不存在,全部失败

项目里使用org.springframework.mail.javamail.JavaMailSender发送邮件,发现一个情况,当收件人列表有一个人不存在,就会导致整个邮件发送失败,结合相关资料,现解决方法如下,感觉整个方法不太好,有更好的方法,欢迎评论,不吝赐教。

@Override
public boolean sendMail(String templeteId, List<String> to) throws Exception {
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    boolean r = false;
    try {
        helper.setFrom("report@xxx.com");
        InternetAddress[] sendTo = new InternetAddress[to.size()];
        for (int i = 0; i < to.size(); i++) {
            sendTo[i] = new InternetAddress(to.get(i));
        }
        helper.setTo(sendTo);
        helper.setSubject("定时报表");
        Map res = reportUtil.assembleData(templeteId);
        String html = res.get("html").toString();
        helper.setText(html, true); // 邮件内容,参数true表示是html代码

        if (res.get("subject") != null && StringUtils.isNotBlank(res.get("subject").toString())) {
            helper.setSubject("定时报表-" + res.get("subject").toString());
        }

        if (res.get("filePath") != null && StringUtils.isNotBlank(res.get("filePath").toString())) {
            String filePath = res.get("filePath").toString();
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);
        }
        mailSender.send(message);
        log.info("html邮件已经发送。");
        r = true;
    } catch (Exception e) {
        if (e instanceof MailSendException) {
            for (Exception exception : ((MailSendException) e).getFailedMessages().values()) {
                if (exception instanceof SendFailedException) {
                    for (Address address : ((SendFailedException) exception).getInvalidAddresses()) {
                        to.remove(address.toString());
                        log.info("邮箱地址不存在,{}", address.toString());
                    }
                }
            }
            InternetAddress[] sendTo = new InternetAddress[to.size()];
            for (int i = 0; i < to.size(); i++) {
                sendTo[i] = new InternetAddress(to.get(i));
            }
            try {
                helper.setTo(sendTo);
                mailSender.send(message);
                r = true;
            } catch (Exception e1) {
                log.error("二次发送邮件失败",e1);
            }
        }
        if (!r) {
            log.error("邮件发送失败", e);
        }
    }
    return r;
}
本原创文章未经允许不得转载 | 当前页面:PME-Blog » Java邮件发送一个收件人不存在,全部失败

评论