简体   繁体   English

显示为附件的内嵌图像:JavaMail

[英]Inline image shown as attachment : JavaMail

I am trying to send an email with an inline image, but the image is getting send as an attachment instead of inline.我正在尝试发送带有内嵌图像的电子邮件,但图像作为附件而不是内嵌发送。

 MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        String filename = "logo.jpeg";

        mimeMessage.setFrom(new InternetAddress("Bridge"));
        mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        mimeMessage.setSubject(subject);

        MimeMultipart multipart = new MimeMultipart();

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html");

        multipart.addBodyPart(messageBodyPart);
        messageBodyPart = new MimeBodyPart();

        DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(resourceFile.getInputStream()), MediaType.IMAGE_JPEG_VALUE);
        messageBodyPart.setDataHandler(new DataHandler(fds));
        messageBodyPart.setDisposition(MimeBodyPart.INLINE);
        messageBodyPart.setFileName(filename);
        messageBodyPart.setHeader("Content-ID", "<logoimg>");
        messageBodyPart.setHeader("Content-Type", MediaType.IMAGE_JPEG_VALUE);

        multipart.addBodyPart(messageBodyPart);

        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();

        javaMailSender.send(mimeMessage);
   }  catch (MailException | MessagingException | IOException e) {
        log.warn("Email could not be sent to user '{}'", to, e);
   }

And here is my HTML code for the image:这是我的图像 HTML 代码:

<img width="100" height="50" src="|cid:logoimg|" alt="phoenixlogo"/>

I have tried all the multipart types: "mixed", "relative", "alternative" but couldn't get it to work.我已经尝试了所有的多部分类型:“混合”、“相对”、“替代”,但无法让它发挥作用。

Here is image for same:这是相同的图像: 在此处输入图片说明

You don't want an inline image, you want an html body that references an attached image.您不需要内嵌图像,而是需要引用附加图像的 html 正文。 For that you need a multipart/related message.为此,您需要一个多部分/相关消息。 See the JavaMail FAQ .请参阅JavaMail 常见问题解答

You need to add a separate MimeBodyPart : For Example您需要添加一个单独的MimeBodyPart :例如

            BodyPart imgPart = new MimeBodyPart();

            DataSource ds = new FileDataSource("D:/image.jpg");
            imgPart.setDataHandler(new DataHandler(ds));
            imgPart.setHeader("Content-ID", "<the-img-1>");
            multipart.addBodyPart(imgPart);

Then in the html you refer to the Image as:然后在 html 中,您将图像称为:

<br>" + "<img src=\"cid:the-img-1\"/><br/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM