繁体   English   中英

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

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

我已经成功地遵循了有关如何使用javamail将图像嵌入HTML的教程。 但是,我现在正尝试从模板html文件中读取内容,然后在发送之前将图像嵌入其中。

我确定该代码适用于嵌入图像,就像我使用时一样:

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();  
bodyPart.setContent(str, "text/html");

电子邮件发送时图像不会显示。

我的读取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;
  }
}

我发送电子邮件的完整课程如下:

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

我已经阅读了许多有关此问题的答案,但真的不确定为什么会这样。 我以为是因为我的html文件有问题,但是我使用与上面的初始setContent代码相同的内容创建了一个非常基本的文件,并且图片没有出现在此基本示例中。

与读入字节数组有关吗?

任何帮助,不胜感激。

谢谢

电子邮件客户端解释HTML代码的方式与写入HTML模板文件的方式不同。 但是您可以确定的一件事是,一旦获得模板,请将图像的字节数组复制到src属性。 您可以尝试将内联图像用作浏览器的inteprets src属性,并发出另一个请求以获取数据。

使您对这个概念有更多的了解。 HTML内联图像

当然,您需要确保文件中的数据实际上是使用UTF-8编码的,而不是计算机的默认编码。 如果您使用所有ASCII文本进行测试,则没关系。

假设文件中的文本与上面的示例代码中的字符串中的文本相同,则可以比较两种情况(字符串,文件),以查看JavaMail通过使用message.writeTo(new FileOutputStream( “ msg.txt”)); 就在Transport.send调用之前或代替它。

暂无
暂无

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

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