2

Hi I have the following code:

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

It works fine if I use

 

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

   instead of

DataSource fds = new FileDataSource(emailImage);

But I want to access image from WebContent->images.
I get java.lang.NullPointerException when I run this.

Gidil
  • 4,137
  • 2
  • 34
  • 50
user1746981
  • 21
  • 1
  • 2

3 Answers3

0

If you would like to use in web application. First, you have to upload your attachment file to server as InputStream and then create attachment file by using this InputStream.

maxstreifeneder
  • 625
  • 1
  • 8
  • 19
Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131
0

Solved: Use getRealPath(); Its working fine now.

File contextDir = new File(request.getRealPath("/images/sample.jpeg"));
DataSource fds = new FileDataSource(contextDir);

user1746981
  • 21
  • 1
  • 2
0

If images/sample.jpeg is from your resources folder then try this :

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

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

in case of non static reference:

return new File(getClass().getClassLoader().getResource(fileName).getFile());
Alferd Nobel
  • 3,185
  • 2
  • 30
  • 35