I'm trying to send mails with multiple images embedded into the body.... I was reding this Sending mail along with embedded image using javamail, but unfortunately I can't get works
Creating the Message
javax.mail.Message message = new javax.mail.internet.MimeMessage(Session.getInstance(mailingSettings.getProperties()));
message.setFrom(new InternetAddress(mailingSettings.getCorreoOrigen(), mailingSettings.getNombreOrigen()));
message.setSentDate(new Date());
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailDTO.getCorreoDestino()));
message.addHeader("Content-type", "text/HTML; charset=iso-8859-1");
message.addHeader("Content-Transfer-Encoding", "8bit");
message.setSubject(mailDTO.getAsunto() + mailDTO.getCodigoDocumento() + "-sendOneMail");
Now I create Multipart
MimeMultipart multipart = new MimeMultipart();
// Ini Add the Body
BodyPart mimeBodyPart = new PreencodedMimeBodyPart("8bit");
mimeBodyPart.setContent(contenidoCorreo /*The HTML with multiple images*/, "text/html");
multipart.addBodyPart(mimeBodyPart);
// End Add the Body
addImages2(mailDTO, multipart, contenidoCorreo);
try {
message.setContent(multipart); //Add the Multipart to the Message
Transport.send(message); //Send the Message
} catch (Exception e) {
e.printStackTrace();
throw e;
}
Now the method to Add Images to the Multipart
private void addImages2(MailDTO mailDTO, final Multipart multipart, String contenidoCorreo) throws Exception {
//Check the 'cid' words and get the image names....
Set<String> setImagenes = Arrays.stream(contenidoCorreo.split("cid:")).collect(Collectors.toSet());
setImagenes.stream().forEach(stringCid -> {
String imagenCid = (stringCid.split("\""))[0];
String pathImage = /path/to/Images/Directory + "/" + imagenCid;
if (new File(pathImage).exists()) {
BodyPart imagenMimeBodyPart = new MimeBodyPart();
try {
DataSource source = new FileDataSource(pathImage);
imagenMimeBodyPart.setDataHandler(new DataHandler(source));
imagenMimeBodyPart.setFileName(imagenCid);
imagenMimeBodyPart.setHeader("Content-ID", imagenCid);
multipart.addBodyPart(imagenMimeBodyPart);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
All images are sent like atachment, but not inserted into HTML.
Now, I will compare the Content Message using Successfully Telnet method...
In the Left Side using Telnet directly method, in the rigth Side my Java code.
Comparing the inital snippet with the HTML Body Content
Comparing the final snippet of HTML Body Content
Some part of the images separation using Telnet Method on left Side
The final part using Telnet Method!
The Email with attached images
How fix my code in order to show the images inserted in my HTML code and that the images are displayed too?