繁体   English   中英

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

[英]Sending mail along with embedded image using 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);

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

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

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

更改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");

尝试摆脱以下行:

messageBodyPart.setDisposition("inline");

我偶然发现了类似的问题。 以下帖子对我有很大帮助: 如何使用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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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