使用javamail发送邮件和嵌入式图像

我想发送邮件和嵌入式图像。 为此,我使用了以下代码。 它不是完整的代码。 它是代码的一部分

Multipart multipart = new MimeMultipart("related"); // Create the message part BodyPart messageBodyPart; messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(msgBody); // msgbody contains the contents of the html file messageBodyPart.setHeader("Content-Type", "text/html"); multipart.addBodyPart(messageBodyPart); //add file attachments DataSource source; File file = new File("D:/sample.jpeg"); if(file.exists()){ // add attachment messageBodyPart = new MimeBodyPart(); source = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(file.getName()); messageBodyPart.setHeader("Content-ID", ""); messageBodyPart.setDisposition("inline"); multipart.addBodyPart(messageBodyPart); } // Put parts in message msg.setContent(multipart); Transport.send(msg); 

我面临的问题是,我可以收到邮件,但不能看到图像..它不会显示在邮件中。
下面是我的html文件部分

  Barcode 

请帮助我为什么图片没有显示在邮件中,为什么它不在附件?

尝试删除以下行:

 messageBodyPart.setDisposition("inline"); 

改变new MimeMultipart("related");new MimeMultipart(); (以及msg.setContent(multipart);以及msg.setContent(multipart,"multipart/related"); )另外请确保将img src=\"cid:BarcodeImage\"更改为img src="cid:BarcodeImage" 。 它应该工作。

将“相对”更改为“替代”,然后您将图像作为附件。

  Multipart multipart = new MimeMultipart("alternative"); 

我偶然发现了类似的问题。 以下post帮助了我很多: 如何使用Java发送包含嵌入式图像的电子邮件代码中最重要的部分是:

 String cid = generateCID(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText("" + "This is not usually displayed" + "n" + "
Hi there!
" + "
Sending HTML in email is so cool!
n" + "
And here's an image:
" + "
I hope you like it!
", "US-ASCII", "html"); content.addBodyPart(textPart); MimeBodyPart imagePart = new MimeBodyPart(); imagePart.attachFile("resources/teapot.jpg"); imagePart.setContentID("<" + cid + ">"); imagePart.setDisposition(MimeBodyPart.INLINE); content.addBodyPart(imagePart);

函数generateCID()必须返回唯一的String。 例如:

 java.util.UUID.randomUUID()