4

我想在我的邮件中添加多张图片

String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email-template.vm", module);
            message.setText(text, true);

            message.addInline("img001", new ClassPathResource("/myPath/image001.jpg"));
            message.addInline("img002", new ClassPathResource("/myPath/image002.jpg"));

但我有一个 NullPointerException !

org.springframework.mail.MailPreparationException: Could not prepare mail; nested exception is java.lang.NullPointerException
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:369) [spring-context-support-2.5.6.SEC01.jar:2.5.6.SEC01]
at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:346) [spring-context-support-2.5.6.SEC01.jar:2.5.6.SEC01]

当我只添加一张图片(addInline())时一切顺利,邮件已发送

有人有想法吗?谢谢

编辑:

我想出了如何发送包含多个图像的电子邮件

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
         public void prepare(MimeMessage mimeMessage) throws Exception {
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage,MimeMessageHelper.MULTIPART_MODE_RELATED,"UTF-8");
                    message.setTo(TO);
                    message.setFrom(FROM);
    MimeBodyPart part = new MimeBodyPart();
    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,"template.vm","UTF-8",module);
    part.setContent(body,"text/html");
// Create a new part for the attached image and set the CID image identifier
    MimeBodyPart imagePart = new MimeBodyPart();
    FileDataSource fds = new FileDataSource("C:/path/image001.jpg");
    imagePart.setDataHandler(new DataHandler(fds));
    imagePart.setHeader("Content-ID", "resImg1");

    MimeBodyPart imagePart2 = new MimeBodyPart();
    FileDataSource fds2 = new FileDataSource("C:/image002.jpg");
    imagePart2.setDataHandler(new DataHandler(fds2));
    imagePart2.setHeader("Content-ID", "resImg2");

    Multipart mp = new MimeMultipart();

    mp.addBodyPart(part);
    mp.addBodyPart(imagePart);
    mp.addBodyPart(imagePart2);

    // Set the message's content
    mimeMessage.setContent(mp);
    }
};
this.mailSender.send(preparator);

在 template.vm 中插入图片:<img width=172 height=40 src="cid:resImg1"alt="Image1"/>

我希望能帮助别人

4

0 回答 0