如何使用 javamail 添加内联图像?

How to add a inline image using javamail?

我想将内联图像发送到电子邮件。我几乎尝试了所有可能的方法,但没有成功。

我可以添加内联图片,但它们也出现在附件中,所以我无法避免此附件。

messageBodyPart = new MimeBodyPart();
            String htmlText = "<H1>This is the image: </H1><img src=\"cid:image\">";
            ((MimeBodyPart) messageBodyPart).setText(htmlText, null, "html");
            mp.addBodyPart(messageBodyPart);

            // second part (the image)
            messageBodyPart = new MimeBodyPart();
            String filePath = "abc.png";
            ((MimeBodyPart) messageBodyPart).attachFile(filePath, "image/png", "base64");
            ((MimeBodyPart) messageBodyPart).setContentID("<image>");
            mp.addBodyPart( messageBodyPart );

我也试过使用messageBodyPart.setDisposition( MimePart.INLINE );,但还是不行。

考虑使用 MimeMessageHelper。它会让你的生活更轻松

MimeMessageHelper helper = new MimeMessageHelper( mimeMessage, true );
helper.setText( htmlText, true );
helper.addInline( "image", signatureImage ); // image here is the cid

您需要创建一个 multipart/related 消息。 JavaMail FAQ有个例子。