2

嗨,我有以下代码:

    MimeMessage msg = new MimeMessage(session);
    InternetAddress addressFrom = new InternetAddress("krao346789@gmail.com");
    msg.setFrom(addressFrom);

    InternetAddress[] addressTo = new InternetAddress[sendTo.length];
    for (int i = 0; i < sendTo.length; i++) {
    addressTo[i] = new InternetAddress(sendTo[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);

    // Setting the Subject and Content Type
    msg.setSubject(emailSubjectTxt);
    /*Image part*/

    MimeMultipart multipart = new MimeMultipart("related");  

    // first part  (the html)  
    BodyPart messageBodyPart = new MimeBodyPart();  
    String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";  
    messageBodyPart.setContent(htmlText, "text/html");  

    // add it  
    multipart.addBodyPart(messageBodyPart);  

    // second part (the image)  
    messageBodyPart = new MimeBodyPart();  
    String contextPath=request.getContextPath();
    System.out.println("contextpath"+contextPath);
    File contextDir = new File(contextPath);  
    System.out.println("contextDir"+contextDir);
    File emailImage = new File(contextDir, "/images/sample.jpeg"); 
    System.out.println("emailImage"+emailImage);

    DataSource fds = new FileDataSource(emailImage);  
    //System.out.println("fds"+fds.getName());
    messageBodyPart.setDataHandler(new DataHandler(fds));  
    messageBodyPart.setHeader("Content-ID","<image>");  

    // add it  
    multipart.addBodyPart(messageBodyPart);  

    // put everything together  
    msg.setContent(multipart);  
    Transport.send(msg);
}

如果我使用它工作正常

 

DataSource fds = new FileDataSource("C:\\images\\sample.jpeg");

   代替

DataSource fds = new FileDataSource(emailImage);

但我想从WebContent->images. 当我运行这个时,
我得到了。java.lang.NullPointerException

4

3 回答 3

0

已解决:使用getRealPath();它现在工作正常。

文件 contextDir = new File(request.getRealPath("/images/sample.jpeg"));
数据源 fds = new FileDataSource(contextDir);

于 2012-10-17T11:04:53.183 回答
0

如果您想在 Web 应用程序中使用。首先,您必须将附件文件上传到服务器InputStream,然后使用此创建附件文件InputStream

于 2012-10-15T12:53:52.953 回答
0

如果images/sample.jpeg来自您的资源文件夹,请尝试以下操作:

DataSource fds = new FileDataSource(getFileHandle("images/sample.jpeg"));

public static File getFileHandle(String fileName){
       return new File(YourClassName.class.getClassLoader().getResource(fileName).getFile());
}

在非静态引用的情况下:

return new File(getClass().getClassLoader().getResource(fileName).getFile());
于 2021-02-03T07:06:51.473 回答