我正在做Java Web应用程序,我正在邮件正文中发送邮件,我需要显示图像,但当我发送邮件时,它需要图像附件,我不想附加我需要在正文内容中显示图像。有人能告诉我如何做到这一点吗
发布于 2017-08-08 06:16:23
就像@scary-袋熊提到的那样,你没有添加第一杆。我想你的本意是:
...
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
...
您还可以将Content-Disposition头部添加到镜像部分:
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
更新:
抱歉,您还必须提前创建multipart:
...
// add it
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart);
// second part (the image)
...
更新2:
试试这个:
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
// add it
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
java.io.InputStream inputStream = this.getClass().getResourceAsStream("/HappyBirthday.JPG");
ByteArrayDataSource ds = new ByteArrayDataSource(inputStream, "image/jpg");
System.out.println(inputStream);
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setHeader("Content-ID", "<image>");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
// Send message
Transport.send(message);
发布于 2017-08-08 05:27:15
如果你看一下你的代码
messageBodyPart.setContent(htmlText, "text/html");
// second part (the image)
messageBodyPart = new MimeBodyPart();
您将看到在尚未添加HTML
部件的情况下正在重新初始化messageBodyPart
我建议您使用不同的对象,然后添加这两个对象
// second part (the image)
messageBodyPart2 = new MimeBodyPart();
....
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);
https://stackoverflow.com/questions/45559834
复制