How can I create an HTML message which will contain multiple images?
Created May 7, 2012
John Zukowski Extending the single image FAQ to multiple images works fine. The extra images should not be treated as attachments, vs. inline images:
import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class HtmlImageExample { public static void main (String args[]) throws Exception { String host = args[0]; String from = args[1]; String to = args[2]; String file = args[3]; String file2 = args[4]; // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host); // Get session Session session = Session.getDefaultInstance(props, null); // Create the message Message message = new MimeMessage(session); // Fill its headers message.setSubject("Embedded Image"); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>Hello</H1>" + "<img src="cid:memememe"><p>" + "<img src="cid:youyouyou">"; messageBodyPart.setContent(htmlText, "text/html"); // Create a related multi-part to combine the parts MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); // Create part for the image messageBodyPart = new MimeBodyPart(); // Fetch the image and associate to part DataSource fds = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID","<memememe>"); // Add part to multi-part multipart.addBodyPart(messageBodyPart); // Create 2nd part for the image messageBodyPart = new MimeBodyPart(); // Fetch the image and associate to part DataSource fds2 = new FileDataSource(file2); messageBodyPart.setDataHandler(new DataHandler(fds2)); messageBodyPart.setHeader("Content-ID","<youyouyou>"); // Add part to multi-part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message message.setContent(multipart); // Send message Transport.send(message); } }