gpt4 book ai didi

java - 如何在使用 Java 邮件发送 html 电子邮件时嵌入多个图像

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:41 26 4
gpt4 key购买 nike

我正在尝试从 javamail 发送电子邮件。我正在嵌入图像并使用 CID。但问题是如何在一条消息中嵌入多个图像。如果我尝试添加 header .. 它只是采用最后设置的 header 。如何使用 CID 添加多个图像和引用。

MimeMultipart multipart = new MimeMultipart("related");

// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
// BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><br/> <p align=center><img src=\"cid:senny\"> </p>";
htmlText+="<p align=center><img src=\"cid:senny\"> </p>";
htmlText+="<p align=center><img src=\"cid:image\"> </p>";
messageBodyPart.setContent(htmlText, "text/html");

// add it
multipart.addBodyPart(messageBodyPart);

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
("C:\\images\\cec_header_457.png");
DataSource fds1 = new FileDataSource
("C:\\images\\cec_header_420.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setDataHandler(new DataHandler(fds1));
messageBodyPart.addHeader("Content-ID","<image>");
messageBodyPart.addHeader("Content-ID","<senny>");
// add it
multipart.addBodyPart(messageBodyPart);

// put everything together
message.setContent(multipart);

最佳答案

每张图片都需要有自己的MimeBodyPart,分解这段代码,

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
("C:\\images\\cec_header_457.png");
DataSource fds1 = new FileDataSource
("C:\\images\\cec_header_420.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setDataHandler(new DataHandler(fds1));
messageBodyPart.addHeader("Content-ID","<image>");
messageBodyPart.addHeader("Content-ID","<senny>");
// add it
multipart.addBodyPart(messageBodyPart);

分为两个多部分,类似

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds1 = new FileDataSource
("C:\\images\\cec_header_420.png");
messageBodyPart.setDataHandler(new DataHandler(fds1));
messageBodyPart.addHeader("Content-ID","<senny>");
// add it
multipart.addBodyPart(messageBodyPart);

messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
("C:\\images\\cec_header_457.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.addHeader("Content-ID","<image>");
// add it
multipart.addBodyPart(messageBodyPart);

关于java - 如何在使用 Java 邮件发送 html 电子邮件时嵌入多个图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5848669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com