简体   繁体   English

Javamail HTML模板的电子邮件中未显示嵌入式图像

[英]Embedded images not showing in email from Javamail html template

I have successfully followed tutorials of how to embed images into HTML with javamail. 我已经成功地遵循了有关如何使用javamail将图像嵌入HTML的教程。 However i am now trying to read from a template html file and then embed images into this before sending. 但是,我现在正尝试从模板html文件中读取内容,然后在发送之前将图像嵌入其中。

I am sure that the code is right for the embedding images as when i use: 我确定该代码适用于嵌入图像,就像我使用时一样:

bodyPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
               "<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");

The images display fine. 图像显示良好。 However when i read from a file using: 但是,当我使用以下命令从文件中读取内容时:

readHTMLToString reader = new readHTMLToString();
String str = reader.readHTML();  
bodyPart.setContent(str, "text/html");

The images do not show up when the email sends. 电子邮件发送时图像不会显示。

My code for reading the html to string is as follows: 我的读取html到字符串的代码如下:

public class readHTMLToString {
static String finalFile;

public static String readHTML() throws IOException{

//intilize an InputStream
    File htmlfile = new File("C:/temp/basictest.html");
    System.out.println(htmlfile.exists());
try {
  FileInputStream fin = new FileInputStream(htmlfile);

  byte[] buffer= new byte[(int)htmlfile.length()];
new DataInputStream(fin).readFully(buffer);
    fin.close();
    String s = new String(buffer, "UTF-8");
    finalFile = s;
}
catch(FileNotFoundException e)
{
  System.out.println("File not found" + e);
}
catch(IOException ioe)
{
  System.out.println("Exception while reading the file " + ioe);
}
return finalFile;
  }
}

My complete class for sending the email is as follows: 我发送电子邮件的完整课程如下:

package com.bcs.test;

import java.io.IOException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendEmail {

public static void main(String[] args) throws IOException {

    final String username = "usernamehere@gmail.com";
    final String password = "passwordhere";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");


    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
      });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from-email@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("recepientemailhere"));
        message.setSubject("Testing Subject");

        //SET MESSAGE AS HTML
        MimeMultipart multipart = new MimeMultipart("related");  

        // Create bodypart.  
        BodyPart bodyPart = new MimeBodyPart();  

        // Create the HTML with link to image CID.  
        // Prefix the link with "cid:". 

        //bodyPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
              // "<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");
        readHTMLToString reader = new readHTMLToString();
        String str = reader.readHTML();  

        // Set the MIME-type to HTML.  
        bodyPart.setContent(str, "text/html");  

        // Add the HTML bodypart to the multipart.  
        multipart.addBodyPart(bodyPart);  

        // Create another bodypart to include the image attachment.  
        BodyPart imgPart = new MimeBodyPart();  

        // Read image from file system.  
        DataSource ds = new FileDataSource("C:\\temp\\dice.png");  
        imgPart.setDataHandler(new DataHandler(ds));  

        // Set the content-ID of the image attachment.  
        // Enclose the image CID with the lesser and greater signs. 
        imgPart.setDisposition(MimeBodyPart.INLINE);
        imgPart.setHeader("Content-ID","the-img-1");
        //bodyPart.setHeader("Content-ID", "<image_cid>");  

        // Add image attachment to multipart.  
        multipart.addBodyPart(imgPart);  

        // Add multipart content to message.  
        message.setContent(multipart);  



        //message.setText("Dear Mail Crawler,"
        //  + "\n\n No spam to my email, please!");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
}

Ive read through numerous answers about this but really not sure why this is happening. 我已经阅读了许多有关此问题的答案,但真的不确定为什么会这样。 I thought it was because of an issue with my html file however i created a very basic one using the same content as the initial setContent code above and the pictures dont appear in this basic example. 我以为是因为我的html文件有问题,但是我使用与上面的初始setContent代码相同的内容创建了一个非常基本的文件,并且图片没有出现在此基本示例中。

Something to do with reading into a byte array? 与读入字节数组有关吗?

Any help greatly appreciated. 任何帮助,不胜感激。

Thanks 谢谢

The way email clients interpret HTML code is different from writing to HTML template file. 电子邮件客户端解释HTML代码的方式与写入HTML模板文件的方式不同。 But one thing you could try for sure is once you get the template, copy the byte array of the image to the src attribute. 但是您可以确定的一件事是,一旦获得模板,请将图像的字节数组复制到src属性。 You could try with inline images as browser inteprets src attribute and make another request to get the data. 您可以尝试将内联图像用作浏览器的inteprets src属性,并发出另一个请求以获取数据。

Gives you a lot more insight in to the concept. 使您对这个概念有更多的了解。 Inline Images in HTML HTML内联图像

Of course you need to make sure that the data in the file is actually encoded in UTF-8 and not in the default encoding for your computer. 当然,您需要确保文件中的数据实际上是使用UTF-8编码的,而不是计算机的默认编码。 If you test this with all ASCII text, it shouldn't matter. 如果您使用所有ASCII文本进行测试,则没关系。

Assuming you have the same text in the file that you have in the string in the sample code above, you can compare the two cases (string, file) to see how the messages JavaMail would send differ by using message.writeTo(new FileOutputStream("msg.txt")); 假设文件中的文本与上面的示例代码中的字符串中的文本相同,则可以比较两种情况(字符串,文件),以查看JavaMail通过使用message.writeTo(new FileOutputStream( “ msg.txt”)); just before or in place of the Transport.send call. 就在Transport.send调用之前或代替它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM