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.
01.Properties sessionProperties = System.getProperties();02.sessionProperties.put("mail.smtp.host", smtpServer);03.Session session = Session.getDefaultInstance(sessionProperties, null);04. 05.// Create message06. 07.Message message = new MimeMessage(session);08.message.setFrom(new InternetAddress(from));09.message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(10. to, false));11.message.setSubject(subject);12. 13.// Add html content14.// Specify the cid of the image to include in the email15. 16.String html = "<html><body><b>Test</b> email <img src='cid:my-image-id'></body></html>";17.Multipart mp = new MimeMultipart();18.MimeBodyPart htmlPart = new MimeBodyPart();19.htmlPart.setContent(html, "text/html");20.mp.addBodyPart(htmlPart);21. 22.// add image in another part23. 24.MimeBodyPart imagePart = new MimeBodyPart();25.DataSource fds = new FileDataSource(imagePath);26.imagePart.setDataHandler(new DataHandler(fds));27.// assign a cid to the image28.imagePart.setHeader("Content-ID", "my-image-id");29.mp.addBodyPart(imagePart);30. 31. 32.message.setContent(mp);33. 34.// Send the message35. 36.Transport.send(message);Read full article from How to embed images in HTML mail using JavaMail | web development helpdesk
No comments:
Post a Comment