2

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

        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", "<BarcodeImage>");
            messageBodyPart.setDisposition("inline");
            multipart.addBodyPart(messageBodyPart);
        }

        // Put parts in message
        msg.setContent(multipart);
        Transport.send(msg);

我面临的问题是,我可以收到邮件,但无法看到图像。它没有显示在邮件中。
下面是我的 html 文件的一部分

             <img src=\"cid:BarcodeImage\" alt="Barcode" width="166" height="44" align="right" />

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

4

4 回答 4

2

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

String cid = generateCID();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("<html><head>"
+ "<title>This is not usually displayed</title>"
+ "</head>n"
+ "<body><div><strong>Hi there!</strong></div>"
+ "<div>Sending HTML in email is so <em>cool!</em> </div>n"
+ "<div>And here's an image: <img src=\"cid:\"" + cid + " /></div>" 
+ "<div>I hope you like it!</div></body></html>",
"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() 必须返回唯一的字符串。例如:

java.util.UUID.randomUUID()
于 2016-05-19T09:54:18.413 回答
1

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

    Multipart multipart = new MimeMultipart("alternative");
于 2018-04-09T10:03:21.123 回答
0

尝试摆脱以下行:

messageBodyPart.setDisposition("inline");
于 2009-06-10T08:32:52.017 回答
0

更改new MimeMultipart("related");new MimeMultipart();(也可选择更改msg.setContent(multipart);msg.setContent(multipart,"multipart/related");) 还要确保更改img src=\"cid:BarcodeImage\"img src="cid:BarcodeImage". 它应该工作。

于 2015-04-13T13:43:46.623 回答