Reputation: 31
I am doing Java Web application, I am sending mails in that mail body i need to display image but when i send mail it takes image attachment i don't want to attachment i need to show the image in body content can anyone please tell me how to do this
Upvotes: 1
Views: 4676
Reputation: 9650
As @scary-wombat mentioned, you didn't add the first par. I suppose you meant to do:
...
// add it
multipart.addBodyPart(messageBodyPart);
// second part (the image)
...
You can also add a Content-Disposition header to the image part:
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
UPDATE:
Sorry, you must also move up the creation of multipart:
...
// add it
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart);
// second part (the image)
...
UPDATE 2:
Try this:
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
// add it
MimeMultipart multipart = new MimeMultipart("related");
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
java.io.InputStream inputStream = this.getClass().getResourceAsStream("/HappyBirthday.JPG");
ByteArrayDataSource ds = new ByteArrayDataSource(inputStream, "image/jpg");
System.out.println(inputStream);
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setHeader("Content-ID", "<image>");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
// Send message
Transport.send(message);
Upvotes: 2
Reputation: 44844
If you look at your code
messageBodyPart.setContent(htmlText, "text/html");
// second part (the image)
messageBodyPart = new MimeBodyPart();
you will see that you are re-initializing messageBodyPart
whilst the HTML
parts hasn't yet been added
I suggest that you use a different Object and then add both
// second part (the image)
messageBodyPart2 = new MimeBodyPart();
....
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);
Upvotes: 0