简体   繁体   中英

How to add a inline image using javamail?

I want to send a inline image to an email. I tried almost all possible ways, but no luck.

I am able to add images as inline, but they were also appearing in attachments, so I am not able to avoid this attachment.

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 );

I also tried using messageBodyPart.setDisposition( MimePart.INLINE ); , but still no luck.

Look into using the MimeMessageHelper. It will make your life a bunch easier

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

You need to create a multipart/related message. The JavaMail FAQ has an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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