Skip to Content
Former Member
Oct 25, 2007 at 07:32 AM

Problem with background in java mail HTML format


I would like to send an email with HTML format which includes an image embedded on its background.

The email is sent fine, but I have got the image as attachment instead background.

The code is like following:

public String sendMail() throws Exception{
	try {
		String host = "xxxxx";
		String from = "";
		String to =   "";   
		String file = "E://Resources//Images//****_MAIL.jpg";

		// Get system properties
		Properties props = System.getProperties();

		// Setup mail server
		props.put("", "xxxxxx");

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

		// Set the HTML content, be sure it references the attachment
		String htmlText =

"< body " background=" " + ""cid:memememe">" +
		"<table id="maintbl"  style="width: 730px"  >"  +
		"<tr> <td><b> Test Test Test Test  </b></td></tr></table></table></body>";

		messageBodyPart.setContent(htmlText, "text/html");

		// Create a related multi-part to combine the parts
		MimeMultipart multipart = new MimeMultipart("related");

		// Add body part to multipart

		// 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));
		// Add a header to connect to the HTML

		// Add part to multi-part

		// Associate multi-part with message

		// Send message
		return "good" ;
}catch (Exception e) {
	//System.out.println("Exception " + e.getMessage());
	return "bad " + e.getMessage();