如何使用HTML模板在Java电子邮件中添加图像

时间:2018-07-03 11:30:54

标签: java html email

我正尝试在java中发送带有图片的电子邮件,但是我无法发送图片,有人可以让我知道,为什么它不起作用,我正在使用{ {1}}。我在做什么错了?

html template文件SendEmail.java如下。

code

` //Email settings code here MimeMultipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(FROM,FROMNAME)); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); String image ="<img src=\"cid:image\">"; msg.setSubject(SUBJECT); DataSource fds = new FileDataSource("C:\\images\\web_logo_white.0e72366a.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); Map<String, String> input = new HashMap<String, String>(); if (msgBody.contains("Summary page was not")) { input.put("logo", image); }else{ // else block and other code continues here } 我要在其中添加图像的地方

HTML file

我正在<table bgcolor="#f9f9f9" width="100%"> <tr> <td>logo<h2><font color="#9d9d9d" ><b><center>Company Logo<center></b></font></h2> </td> </tr> </table> 的setContent部分中发送此html文件

1 个答案:

答案 0 :(得分:0)

像这样流图像

InputStream imageStream = YOurClass.class.getClass().getResourceAsStream("images/web_logo_white.0e72366a.png");
DataSource fds = new ByteArrayDataSource(IOUtils.toByteArray(imageStream), "image/png");
messageBodyPart.setDataHandler(new DataHandler(fds));
multipart.addBodyPart(messageBodyPart);