|
Aug
12
|
Multipart emails can be used to send html content with JavaMail. If you want to use images in the html content you can either specify the url of the image on an external server, or you can embed the image in the email itself.
To embed an image in your mail you need to assign it a cid, which you can then reference in your html img tag. Here is an example that demonstrates embedding an image and use of cid.
Properties sessionProperties = System.getProperties();
sessionProperties.put("mail.smtp.host", smtpServer);
Session session = Session.getDefaultInstance(sessionProperties, null);
// Create message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
to, false));
message.setSubject(subject);
// Add html content
// Specify the cid of the image to include in the email
String html = "<html><body><b>Test</b> email <img src='cid:my-image-id'></body></html>";
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html");
mp.addBodyPart(htmlPart);
// add image in another part
MimeBodyPart imagePart = new MimeBodyPart();
DataSource fds = new FileDataSource(imagePath);
imagePart.setDataHandler(new DataHandler(fds));
// assign a cid to the image
imagePart.setHeader("Content-ID", "my-image-id");
mp.addBodyPart(imagePart);
message.setContent(mp);
// Send the message
Transport.send(message);



November 3rd, 2010 at 4:33 pm
thx for your i get it work with your message and http://java.sun.com/developer/onlineTraining/JavaMail/contents.html
thx again!!
February 18th, 2011 at 5:44 pm
Thanks , it is simple and straightforward
February 18th, 2011 at 5:48 pm
Thats how we like it. Thanks for taking the time to leave a comment.
May 31st, 2011 at 5:51 am
what is the image path should I give when the image is present in the appserver which is deployed along with the ear. I am getting filenot found exception when i give the absolute path on the server
June 1st, 2011 at 10:39 am
Sounds like your image is inside a war in which case you can’t use a FileDataSource. Instead try using a URLDataSource