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

时间:2009-06-10 07:47:55

标签: java email 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", "<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 个答案:

答案 0 :(得分:0)

尝试删除以下行:

messageBodyPart.setDisposition("inline");

答案 1 :(得分:0)

new MimeMultipart("related");更改为new MimeMultipart();(并可选msg.setContent(multipart);改为msg.setContent(multipart,"multipart/related");) 另外,请务必将img src=\"cid:BarcodeImage\"更改为img src="cid:BarcodeImage"。 它应该工作。

答案 2 :(得分:0)

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

    Multipart multipart = new MimeMultipart("alternative");

答案 3 :(得分:-1)

我偶然发现了类似的问题。 以下帖子对我帮助很大: How to send email with embedded images using 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()必须返回唯一的String。 例如:

java.util.UUID.randomUUID()
相关问题