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

Problem with background in java mail HTML format

213 Views

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 = "xxx@ness.com";
		String to =   "xxx@gmail.com";   
		String file = "E://Resources//Images//****_MAIL.jpg";

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

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

		Session session = Session.getDefaultInstance(props, null);
		session.setDebug(true);
		// 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
		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));
		
		 
		// Add a header to connect to the HTML
		messageBodyPart.setHeader("Content-ID","<memememe>");
		//messageBodyPart.addHeader("Content-ID","<memememe>");
		

		// Add part to multi-part
		multipart.addBodyPart(messageBodyPart);

		// Associate multi-part with message
		message.setContent(multipart);

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