嘿我只是想
在我的电子邮件正文中嵌入图像
将在中查看
展望2016
.
多个图像嵌入到身体中
那么我该怎么做呢?
<h1>我有一些附件给你。%img</h1>
其中
被替换一个
与
图像cid名称
当前的代码
只有一个嵌入图像
private static boolean createEmbeddedImg(MimeBodyPart messageBodyPart, Multipart multipart) throws MessagingException, IOException {
int seq = 0;
int c = (seq++) % 100000;
String cid = c + "." + System.currentTimeMillis();
messageBodyPart.setText(""
+ "<html>"
+ " <body>"
+ " <p>Here is my image:</p>"
+ " <img src=\"cid:" + cid + "\" />"
+ " </body>"
+ "</html>"
,"US-ASCII", "html");
multipart.addBodyPart(messageBodyPart);
MimeBodyPart imagePart = new MimeBodyPart();
try {
byte[] decodedImg = Base64.getDecoder().decode(B64.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("c:/temp", "homer.gif");
Files.write(destinationFile, decodedImg);
} catch (IOException e) {
e.printStackTrace();
return false;
}
imagePart.attachFile("c:/temp/homer.gif");
imagePart.setContentID("<" + cid + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imagePart);
multipart.addBodyPart(messageBodyPart);
return true;
}
上面的代码生成一封包含嵌入图像和正文消息的电子邮件:
下面这段代码是我想出的
不止一幅嵌入式图像
在身体里:
private static void _createEmbeddedImgs(MimeBodyPart messageBodyPart, Multipart multipart, String message,
String[] embeddedImgs) throws MessagingException, IOException {
UUID uuid = UUID.randomUUID();
String cid = null;
List<String> savedCIDS = new ArrayList<String>();
if (embeddedImgs != null && embeddedImgs.length > 0) {
for (String filePath : embeddedImgs) {
cid = String.valueOf(uuid.variant());
message = message.replaceFirst("%img", "<img src=\"cid:" + cid + "\" />");
MimeBodyPart imagePart = new MimeBodyPart();
byte[] decodedImg = Base64.getDecoder().decode(B64.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("c:/temp", cid + ".gif");
try {
Files.write(destinationFile, decodedImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imagePart.attachFile("c:/temp/" + cid + ".gif");
imagePart.setContentID("<" + cid + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imagePart);
savedCIDS.add(String.valueOf(cid));
}
messageBodyPart.setText("<html><body>" + message + "</html></body>", "US-ASCII", "html");
multipart.addBodyPart(messageBodyPart);
}
}
这确实会生成一封电子邮件,但看起来是这样的:
所以身体里什么都没有,只有它有嵌入的图像(2.gif)
我似乎无法描绘出我所缺少的东西,以便它也能像我所期望的那样工作。
更新
牧师代码已更改:
int seq = 0;
int c = (seq++) % 100000;
String cid = c + "." + System.currentTimeMillis();
if (embeddedImgs != null && embeddedImgs.length > 0) {
for (String filePath : embeddedImgs) {
message = message.replaceFirst("%img", "<img src=\"cid:" + cid + "\" />");