首页 > 解决方案 > 如何使用 html 模板在 java 电子邮件中添加图像

问题描述

我正在尝试发送java带有图像的电子邮件,但是,我无法这样做,有人可以告诉我,为什么它不起作用,我正在发送电子邮件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>

html在 setContent 部分发送这个文件java

标签: javahtmlemail

解决方案


像这样流式传输图像

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);

推荐阅读