Making Send Mail Web Application with Java

In a websites we often see an interactive feature that can make possible to user to send email to others. This feature is called web-mail. Web mail is a web application which has capability to read and send email through internet browser. There’s a lot of web-mail application that might be we use often. Like yahoo-mail, or Gmail, etc.

In the use of web-mail application, some of developer also use it as a communication tools between user and the internal side of those web-site owner, such as send email to an admin of the web site jut like this link.

Now, we will try to make a send mail web application, for this purpose we will limit the project only to send mail, not read the mail from other mail server. Maybe in the next chance we will discuss about how to read the mail that exist from a mail server.

Ok, now we just go straight…:D

To make this send mail web application with java, we will need some library. Those library is mail.jar and activation.jar. so you can download those library through this link

  1. mail.jar

  2. activation.jar

The process flow of this web application is:

From a standard html form which consist of some input type and a text area, we will posting using HTTP POST method to a servlet that containing methods send mail. And then the status of sending mail will be displayed on a html page.

sendmailflow

 

On the standard html form we need a few input type and a text area. The picture show below hopefully can present.

sendmailform1

And for the servlet scenario, lets arrange with the steps below :

  1. Initialize the smtp host in init servlet methods

  2. Initialize all params that send by standard html form.

  3. On a try-catch block do the following steps:

    • Create java mail session

    • Constructs the message

    • Set the form address and recipient address

    • Set the message

    • Transport the mail

    • Print out the send mail status on html page.

  1. We ca use the catch blok to set the status for causes fo failure send mail process

  2. Print out the send mail status on html page.

To those servlet scenario below is the list of the servlet code.

package org.mojo.mail.web.servlet;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

/**
* Created by IntelliJ IDEA.
* User: Muhammad Yusuf
* Date: 23 Nov 08
* Time: 13:27:09
* To change this template use File | Settings | File Templates.
*/
public class SendMailServlet extends HttpServlet {

private String smtpHost;

//initialize this servlet to get SMTP Host Name to use in sending message
public void init(ServletConfig config) throws ServletException {
   super.init(config);
   smtpHost = config.getInitParameter("smtpHost");
}

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    String from = req.getParameter("from");
    String to = req.getParameter("to");
    String cc = req.getParameter("cc");
    String bcc = req.getParameter("bcc");
    String subject = req.getParameter("subject");
    String text = req.getParameter("text");

    String status;
try {
    //create java mail session
    Properties prop = System.getProperties();
    prop.put("mail.smtp.host", smtpHost);
    Session session = Session.getInstance(prop, null);

    //construct the message
    MimeMessage message = new MimeMessage(session);

    //set the from adress
    Address fromAddress = new InternetAddress(from);
    message.setFrom(fromAddress);

    //parse and set the recipient
    Address[] toAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.TO, toAddress);
    Address[] ccAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.CC, ccAddress);
    Address[] bccAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.BCC, bccAddress);

    //set The Subject and Text
    message.setSubject(subject);
    message.setText(text);

    //begin send Message
    Transport.send(message);
    status = "Your Message has sent";

 } catch (AddressException aex) {
      status = "There was an error when parsing the address";
 } catch (SendFailedException sfe) {
      status = "There was an error when sending the Message";
 } catch (MessagingException me) {
     status = "There was unexpected error";
 }

   //print out status in display
   res.setContentType("text/html");
   PrintWriter writer = res.getWriter();
   writer.println("<html><head><title>Status</title></head>");
   writer.println("<body><p>" + status + "</body></html>");
   writer.close();
 }
}

Let’s discuss those codes.

package org.mojo.mail.web.servlet;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

Just like usual these lines is created to define where the package of this servlet made and importing all the class that might be we need later.

public class SendMailServlet extends HttpServlet {
………..
…….
}

Above code is show us, that we create a servlet class and we name it SendMailServlet, Just because this class is a servlet so we have to add extends HttpServlet there. And then we have to make deployment descriptor(web.xml) file that we will place it at <ApplicationServer>/webapps/<ApplicationName>/WEB-INF/

The deployment descriptor file is shown below:

mail-webxml

On this file we can see that the servlet class that we’ve made, we define here and we name it as sendMessage, and then we will mapping this name to url called /sendMessage. That’s why on the standar html form the action will lead this post to this url. And see that in this file we also initialize a parameter, we named it as smtpHost and the value of this parameter is smtp.speed.net.id, you can change this value depends on which smtp server we use to send the message through this web application

Now let’s see another line of the servlet.

private String smtpHost;

//initialize this servlet to get SMTP Host Name to use in sending message
public void init(ServletConfig config) throws ServletException {
   super.init(config);
   smtpHost = config.getInitParameter("smtpHost");
}

In above code we declare a variable named smtpHost, and this variable is string. Then in the next line we see that this variable now has a value that taken from the web.xml file. This method is using ServletConfig object.

Now let’s see the doPost method below:

public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
   String from = req.getParameter("from");
   String to = req.getParameter("to");
   String cc = req.getParameter("cc");
   String bcc = req.getParameter("bcc");
   String subject = req.getParameter("subject");
   String text = req.getParameter("text");

   String status;
…………
………..
}

Those lines are lines which we take all the value that posted by standard html form and then put it into variables. In this lines we also define a variable that we will use to display the status of the send mail, this variable named status and this is string type.

For the third point of above servlet scenario, we will do it in try-catch block just like the following code.

…………..
try {
    //create java mail session
    Properties prop = System.getProperties();
    prop.put("mail.smtp.host", smtpHost);
    Session session = Session.getInstance(prop, null);

    //construct the message
    MimeMessage message = new MimeMessage(session);

    //set the from adress
    Address fromAddress = new InternetAddress(from);
    message.setFrom(fromAddress);

    //parse and set the recipient
    Address[] toAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.TO, toAddress);
    Address[] ccAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.CC, ccAddress);
    Address[] bccAddress = InternetAddress.parse(to);
    message.setRecipients(Message.RecipientType.BCC, bccAddress);

    //set The Subject and Text
    message.setSubject(subject);
    message.setText(text);

    //begin send Message
    Transport.send(message);
    status = "Your Message has sent";

} catch (AddressException aex) {
…………..
………….

On that code lines, we can see one by one of the servlet scenario on the third point handled, from the making a java mail session till give the value for variable status.

Now let’s see the catch block or a fourth point of servlet scenario.

………….
 } catch (AddressException aex) {
     status = "There was an error when parsing the address";
 } catch (SendFailedException sfe) {
     status = "There was an error when sending the Message";
 } catch (MessagingException me) {
     status = "There was unexpected error";
 }
………….
………….

On that code, we optimize the variable status, we fill this variable with the value that suitable with the error message that can be happen on our servlet. From wrong email address error, till the unexpected error.

Now we meet the last lines of the code.

……..
//print out status in display
        res.setContentType("text/html");
        PrintWriter writer = res.getWriter();
        writer.println("<html><head><title>Status</title></head>");
        writer.println("<body><p>" + status + "</body></html>");
        writer.close();
    }
…….

On this last lines, we make a response as a html type that inform the status of send mail transport. Its easy rite ? now it’s your turn to create and free to modified this all codes for your need.

 

I hope this will be usefull

 

Menteng, November 23rd, 2008

Josescalia

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s