javamail将图像添加到html电子邮件中。怎么样?

时间:2011-03-09 15:48:28

标签: java java-ee ejb-3.0 javamail java-ee-6

1 个答案:

答案 0 :(得分:5)

实现这一目标的一种方法是:

DataSource ds = new ByteArrayDataSource(getServletContext().getResourceAsStream("WEB-INF/resources/images/logomailtemplate.png") ,mimeType);

getServletContext().getResourceAsStream()是从HttpServlet收到并返回InputStream


最好还是这样做

String fileName = "/WEB-INF/resources/images/logomailtemplate.png";
InputStream stream = getServletContext().getResourceAsStream(fileName); //or null if you can't obtain a ServletContext

if (stream == null) {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    if (classLoader == null) {
        classLoader = this.getClass().getClassLoader();
    }

    stream = classLoader.getResourceAsStream(fileName);
}

DataSource ds = new ByteArrayDataSource(stream, "image/*");

<强>更新

可选地

String fileName = "WEB-INF/resources/images/logomailtemplate.png";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
    classLoader = this.getClass().getClassLoader();
}

DataSource ds = new FileDataSource(new File(classLoader.getResource(fileName).toURI()));

//OR
DataSource ds = new URLDataSource(classLoader.getResource(fileName));

确保fileName以“/".

开头