November 28, 2014
Hot Topics:

Creating Java Web Applications for Sending Embedded Images

  • August 17, 2006
  • By Fatima Ahmed
  • Send Email »
  • More Articles »

In most of the e-mails that you receive containing images in the HTML body, those images are not visible. Even if you click the show image option that pops up when you right-click on that image, the problem does not resolve. This is because the <img src> or <embed src> tags in HTML do not work with the e-mail body text, so you need to embed these images inside the e-mail body so that they reach the destination safely.

This article will let you create a Java-based Web application to sending embedded images, text, and HTML in an e-mail body without using attachments.

Requirements

This application is built using Eclipse IDE and the JBoss Application server in a Linux environment. You also can run it on Windows or any other platform. It uses JavaMail and other APIs. Download the APIs along with the resource files to their respective directories as explained in this article and follow the described procedure to create a full-fledged running Web application.

Building the Application

  1. Create a new Java Project by the name of "EmbedEmailExample" with the default settings.
  2. The JRE system library (JDK1.x.x) will automatically be included in your system by default in the Eclipse IDE.
  3. Put your source code (.java files) in a source folder and your compiled classes (.class files) in an output folder. Follow these steps to configure your source and output folders:
    1. Right-click on your project in the Package Explorer.
    2. Go to Properties-->Java Build Path.
    3. Click on the Source tab.
    4. Click on Add Folder.
    5. Click on Create New Folder.
    6. Set the folder name to "src".
    7. Select Yes when it asks you to remove the project as a source folder and to create a "bin" folder.
  4. Next, set your CLASSPATH by defining the libraries (JAR files) that Eclipse should use to compile your code. These jars should be placed in the Project folder or Jboss folder Jboss-x.0.x/server/default/lib (as I did) before navigating to them if they are not present. Add required libraries (jar files) by going to Project--> Properties--> Java Build Path--> Libraries (tab)--> Add External Jars (Button). These are: "mail.jar" (JavaMail API for handling email service), "activation.jar" (JavaActivation API for handling DataSource objects) and "service.jar" (for handling mail connection settings).
  5. Create a new package, "embed.email.utils", by right-clicking on the "src" folder and selecting New--> Package and "WEB-INF" folder to keeping the *.xml (web configuration files) from New--> Folder.
  6. Now, you create java classes inside the created package "embed.email.utils" by right-clicking New--> Class with the default setting of public modifier and having the superclass of java.lang.object as follows: "EmailSenderManager.java" (Listing 1), "EmailTemplateManager.java" (Listing 2), "FileConfigManager.java" (Listing 3), and "FileHelper.java" (Listing 4).

Listing 1: EmailSenderManager.java

package embed.email.utils;

import java.io.File;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.Multipart;
import javax.mail.BodyPart;
import javax.activation.*;
import com.pix.service.ServiceLocator;

import embed.email.utils.FileConfigManager;

public class EmailSenderManager {

private static final String JAVAMAIL_SESSION =
   "java:comp/env/mail/EmbeddedMailSession";
private static EmailSenderManager manager;
protected static final boolean DEBUG = true;
protected Properties mailProperties;

private EmailSenderManager() { }

public static final EmailSenderManager getInstance() {
   if (manager == null) {
      manager = new EmailSenderManager();
   }
   return manager;
}

public void send(Vector toList, String subject, String body) throws
   Exception {

   if( !toList.isEmpty() ){

      Session session = ServiceLocator.getInstance().
         getJavaMailSession(JAVAMAIL_SESSION);
      session.setDebug(DEBUG);
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(""));
      String toAddress = "";
      for (int i = 0; i < toList.size(); i++) {
        toAddress += toList.elementAt(i).toString() + ",";
      }
      toAddress = toAddress.substring(0, toAddress.length() - 1);

      msg.setRecipients(Message.RecipientType.BCC,
                        InternetAddress.parse(toAddress));

      msg.setSubject(subject);
      msg.setText(body);
      msg.setContent(body, "text/html");
      msg.setSentDate(new Date());

      Transport.send(msg);
      if (DEBUG) {
         System.out.println("Message sent OK.");
      }
   }
}

public void sendTextAndHtml(Vector toList, String subject,
                            String textBody, String htmlBody)
   throws Exception {

   if( !toList.isEmpty() ){

      Session session = ServiceLocator.getInstance().
         getJavaMailSession(JAVAMAIL_SESSION);
      session.setDebug(DEBUG);

      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(
         "YourSenderAdress@YourMailServer.com"));
      String toAddress = "";
      //YourRecipientAddresses are defined in the jsp file as a
      //Vector field.
      for (int i = 0; i < toList.size(); i++) {
        toAddress += toList.elementAt(i).toString() + ",";
      }
      toAddress = toAddress.substring(0, toAddress.length() - 1);

      msg.setRecipients(Message.RecipientType.BCC,
                        InternetAddress.parse(toAddress));

      msg.setSubject(subject);

      // Create an "Alternative" Multipart message
      Multipart mp = new MimeMultipart("alternative");

      // for the image part
      BodyPart embedImage1=new MimeBodyPart();
      DataSource ds1=new FileDataSource(new File(
         FileConfigManager.getTemplatesPath() + "logo.jpg"));
      embedImage1.setDataHandler(new DataHandler(ds1));
      embedImage1.setHeader("Content-ID","<logo1>"); 
      /*This cid (content-ID) is passed to the jsp page in the
       *<img src> tag for embedding */
      mp.addBodyPart(embedImage1);

      // for the image part
      BodyPart embedImage2=new MimeBodyPart();
      DataSource ds2=new FileDataSource(new File(FileConfigManager.
         getTemplatesPath() + "logo.gif"));
      embedImage2.setDataHandler(new DataHandler(ds2));
      embedImage2.setHeader("Content-ID","<logo2>");
      mp.addBodyPart(embedImage2);

      // for the text part
      BodyPart bp1 = new MimeBodyPart();
      bp1.setContent(textBody, "text/plain");
      mp.addBodyPart(bp1);

      // for the html part
      BodyPart bp2 = new MimeBodyPart();
      bp2.setContent(htmlBody, "text/HTML");
      mp.addBodyPart(bp2);

      msg.setContent(mp);
      msg.setSentDate(new Date());

      Transport.send(msg);

      if (DEBUG) {
         System.out.println("Message sent OK.");
      }
   }
}
}

Listing 2: EmailTemplateManager.java

package embed.email.utils;

import embed.email.utils.FileConfigManager;
import embed.email.utils.FileHelper;

public class EmailTemplateManager {
   protected static final String
   SHARING_EMAIL_HTML = "SharingEmail.html";
protected static final String
   SHARING_EMAIL_TXT = "SharingEmail.txt";

   private static EmailTemplateManager manager;

protected String TemplateText_html;
protected String TemplateText_txt;

private EmailTemplateManager() throws Exception {

   TemplateText_html = FileHelper.
      loadFromFile(FileConfigManager.getTemplatesPath() +
                   SHARING_EMAIL_HTML);
   TemplateText_txt = FileHelper.
      loadFromFile(FileConfigManager.getTemplatesPath() +
                   SHARING_EMAIL_TXT);

}

public static EmailTemplateManager getInstance() throws Exception {
  if (manager == null) {
    manager = new EmailTemplateManager();
  }
  return manager;
}

public String getEmailTextForSharingEmail_txt(String text_txt,
   String find_txt, String replace_txt) {

   String mailText;

      if(text_txt=="")
         mailText = TemplateText_txt;
      else
         mailText = text_txt;

      text_txt = mailText.replace(find_txt, replace_txt);
      System.out.println(text_txt);

   return text_txt;
}

public String getEmailTextForSharingEmail_html(String html_txt,
   String find_txt, String replace_txt) {
      String mailHtml;

         if(html_txt=="")
            mailHtml = TemplateText_html;
         else
            mailHtml = html_txt;

         //
         html_txt = mailHtml.replace(find_txt, replace_txt);
         //Print on console
         System.out.println(html_txt);

      return html_txt;
   }

}




Page 1 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel