JAVA MAIL API

JavaMail Projects

JavaMail Project 1

Including Image With Your Mail Using JavaMail API
Previous Home Next
adplus-dvertising

If you want to send images then attach images in to your Mesages and then send. you using JavaMail API attach your image. This images attachment and reference the image with a special cid URL, where the cid is a reference to the Content-ID header of the image attachment.

The attaching images or embedding images on your messages like as similar to attaching the file in your message. The only difference for you have to tell the MimeMultipart that the part are related by setting it's subtype. The subtype in the Constructor or setSubType () and set the Content-ID header for the image to a random string which is used as the src for the image in the img tag. The following demonstrates this completely.

package R4R;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
public class ImageAttach {
  public static void main(String args[]) throws Exception {
  Session session = null;
Message message = new MimeMessage(session);
// Fill its headers
message.setSubject("Embedded Image");
String from = null;
message.setFrom(new InternetAddress(from));
String to = null;
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\">"; 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 Object file = null; DataSource fds = new FileDataSource((File) file); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID","<memememe>"); // Add part to multi-part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message message.setContent(multipart); Message forward = null; // Send message Transport.send(forward); System.out.println("The total messages are forward ...."); } }
Previous Home Next