将多个文件添加到Spring mime消息时出错

时间:2018-11-27 22:28:37

标签: java spring-boot mime-message

具有一个表单,当用户填写表单并点击提交时,该表单会通过电子邮件发送。表单上还有一个模式,可以“临时”将文件保存到服务器上的文件夹中。当点击发送表单按钮时,我需要将服务器文件夹中的所有文件附加到表单输入电子邮件中。

尝试使用电子邮件服务文件中的FileSystemResource和helper.addAttachment。还尝试将文件设置为要调用的变量,这两种方式都不适合我。我不断收到Java空指针异常。任何想法如何将所有文件作为附件添加到电子邮件中,或者任何想法出了什么问题?

这里是发送表格的控制器:

@RequestMapping(value="/directBind",  params="send")
    public String send(Model model, @ModelAttribute(value="directBind") DirectBind directBind){
        List<String> businessAgencyList = directBind.getBusinessAgencyList();
        Mail mail = new Mail();
        mail.setFrom("no-reply@example.com");
        mail.setTo(new String[]{"example@example.com"});
        mail.setSubject("Data Checklist");

        Map<String, Object> mailModel = new HashMap<String, Object>();
        mail.setModel(mailModel);

        try {
            emailService.sendSimpleMessage(mail, directBind, storageService);
        } catch (Exception e) {
            e.printStackTrace();
            return ("redirect:/?sentMessageFail");
        }
        return ("redirect:/?sentMessage");
    }

    @RequestMapping(value="/email")
    public String email(){
        return "emailMessage";
    }
}

这是电子邮件服务

public class EmailService {
   private JavaMailSender javaMailSender;

    @Autowired
    public EmailService(JavaMailSender javaMailSender){
        this.javaMailSender = javaMailSender;
    }

    @Autowired
    private SpringTemplateEngine templateEngine;
    
 public void sendSimpleMessage(Mail mail, DirectBind directBind, StorageService storage) throws MessagingException, IOException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message,
                MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
                StandardCharsets.UTF_8.name());

        helper.addAttachment("Mail_Icon.png", new ClassPathResource("static/images/Mail_Icon.png"));

        Context context = new Context();
        context.setVariables(mail.getModel());
        context.setVariable("directBind",directBind);
        String html = templateEngine.process("emailMessage", context);

        helper.setTo(mail.getTo());
        helper.setText(html, true);
        helper.setSubject(mail.getSubject());
        helper.setFrom(mail.getFrom());


        FileSystemResource file= new FileSystemResource(new File(storage.getUploadDir()));
        helper.addAttachment("attachment", file);

        javaMailSender.send(message);
    }
}

0 个答案:

没有答案