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);

written by objects \\ tags: , , ,

Aug 12

Multipart emails can be used to send html content with JavaMail as shown in the following example.


// Create session
    
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);

// Create Multipart to add content to 

Multipart mp = new MimeMultipart();

// Create a Part for the html content

String html = "<html><body><b>Test</b> email</body></html>";
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html");

// Add html part to your Multipart

mp.addBodyPart(htmlPart);

message.setContent(mp);

// Send the message

Transport.send(message);

written by objects \\ tags: , ,