Send Email to selected dropdown user

Send Email to selected dropdown user


Posted in : Servlet Posted on : April 18, 2011 at 4:32 PM Comments : [ 0 ]

This tutorial explains how to send an email to a particular user� from the list.

Send Email to selected dropdown user

This tutorial explains how to send an email to a particular user from the list. An application which we have developed here will help an end user to send an email to a single selected user from the list. To use this application (i.e. to send an email successfully) necessary information should be filled in their corresponding areas in various steps :

Step 1 : Select User from the dropdown list.

Step 2 : Must be enter a valid email ID of sender in the specified area (From) that is this text box could not be empty.

Step 3 : Must be enter a valid email ID of receiver in the specified area (To) that is this text box could not be empty.

Step 4 : Then write your message in message box also this text area could not be empty.

Step 5 : Finally click on submit 'button'. you will find an acknowledgement (in the form of message displaying) of sending the message successfully.

Note : This application will also display an error messages if any incorrect information would be filled by you in their specified area like an invalid email ID or if you keep blank any text field or text area.

To create a such application, we have used JSP, Servlet and Ajax an eclipse IDE environment and run it on 'Tomcat' server. The application directory structure will look like as below, if you are using an Eclipse editor for developing the application.

1119sendemailto_user1.gif

There are the following steps for creating a such application :.

Step 1 :

First we create Dynamic web project "sendemailto_selecteddropdownuser" in eclipse IDE .  Again we create "index.jsp" file under WebContent folder. The code of "index.jsp" are given as:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send email to selected dropdown user</title>
<script type="text/javascript" > 
function addMailBox(selectItem)
{
var index = selectItem.selectedIndex;
var selectedUser = selectItem.options[index].value;
getMailBox(selectedUser);
}
function getMailBox(selectedUser)
{
var url="sendemailbox.jsp?username="+encodeURI(selectedUser); 
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mailbox").innerHTML =xmlhttp.responseText;
}
} 
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
<script type="text/javascript">
function validateForm()
{
var to=document.getElementById("to").value;
var from=document.getElementById("from").value;
var message=document.getElementById("message").value;
if (from==null || from=="")
{
alert("'Fron Email' Field must not be blank.");
document.getElementById("from").focus();
return false;
}
if(checkEmail(from)!=true)
{
alert("'From Email' Not a valid Email.");
document.getElementById("from").focus();
return false;
}
if (to==null || to=="")
{
alert("'To Email' Field must not be blank.");
document.getElementById("to").focus();
return false;
}
if(checkEmail(to)!=true)
{
alert("'To Email' Not a valid Email.");
document.getElementById("to").focus();
return false;
}
if (message==null || message==""){
alert("Message must not be blank.");
document.getElementById("message").focus();
return false;
} 
return true; 
}
function checkEmail(inputvalue){
var pattern=/^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
if(pattern.test(inputvalue)){
return true;
}else{
return false;
}
}
</script>
</head>
<body>
<h3 align="center" >Send email to selected dropdown user</h3>
<form action="sendemail" method="get" 
onsubmit="return validateForm()" >
<table align="center" > 
<tr>
<td>Select User</td>
<td> 
<select style="width:145px;" name=select1 
onchange='addMailBox(this.form.select1);'>
<option>User 1</option>
<option>User 2</option>
<option>User 3</option>
<option>User 4</option>
<option>User 5</option>
<option>User 6</option>
<option>User 7</option>
<option>User 8</option>
<option>User 9</option>
<option>User 10</option>
</select>
</td>
</tr>
</table> 
<div id="mailbox"></div> 
</form> 
</body>
</html>

Step 2 :

Now create class  "EmailSender.java" under " src/net/roseindia" directory . This class used for sending email .The code of  "EmailSender.java" class given below:

package net.roseindia;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class EmailSender{
  public static void sendMail(String from, String[] to,
		  String subject, String content) throws Exception{
	 try {
	  String smtpHost = "192.168.10.105";
	  Properties properties = new Properties();
	  properties.setProperty("mail.smtp.host",smtpHost);
	  Session sesson = Session.getInstance(properties);
	  
	  Message msg = new MimeMessage(sesson);
	  msg.setFrom(new InternetAddress(from));
	  InternetAddress[] toIA = new InternetAddress[to.length];
	  for(int i=0; i<to.length;i++){
		toIA[i]= new InternetAddress(to[i]);
	   }
	  msg.addRecipients(Message.RecipientType.TO, toIA);
	  msg.setSubject(subject);
	  
	  String htmlText = content;
	  msg.setContent(content, "text/html");
	  Transport.send(msg);
	  System.out.println("Message send Successfully....");
	}catch(Exception e){
	  e.printStackTrace();
	  System.out.println("Following Error Occured :"+e.getMessage());
	 }
   }
 }

Step 3 :

Now create class "SendEmailToUser .java" under " src/net/roseindia" directory .This class used for send email to selected dropdown user. The code of  "SendEmailToUser .java" class given below:

package net.roseindia;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.roseindia.EmailSender;

public class SendEmailToUser extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) 
   throws ServletException, IOException {
	 String from=request.getParameter("from");	 
	 String user=request.getParameter("username");
	 //String[] to={request.getParameter("to")};
	 String to[] = new String[]{"b1@localhost"};
	 String subject="send email by admin ";
	 String message=request.getParameter("message");	
	 String content = "<html><body>";
	        content +="<div style='padding-left:10px;" +
	        	"background-color:#CEF6F5;border:1px solid blue;width:100%'>";
	        content += "Hi,";
	        content += "<br>";
	        content +="&nbsp&nbsp&nbsp"+ user;	        
	        content += "<br><br>";
	        content +=message ;
	        content +="<br><br></div>";
	        content += "</body></html>";	 
	 try{
	   EmailSender.sendMail(from, to, subject, content);
	  }catch (Exception e) {
		e.printStackTrace();
	 }	  
	 RequestDispatcher dispatcher=getServletContext().
	 getRequestDispatcher("/sendemailsuccess.jsp");
	 dispatcher.forward(request, response);
  }
}

Step 3 :

Now create "sendemailbox.jsp"  jsp file under WebContent folder. The code of  "sendemailbox.jsp"  given below as:


<%
String username=request.getParameter("username");
%>
<hr width="350" >
<table align="center" >
<tr>
<td>User Name :</td>
<td><input type="text" value="<%=username%>" disabled="disabled" />
<input type="hidden" name="username" value="<%=username%>" /></td>
</tr> 
<tr>
<td>From :</td>
<td><input type="text" name="from" id="from" /></td>
</tr>
<tr>
<td>To :</td>
<td><input type="text" name="to" id="to" /></td>
</tr>
<tr>
<td>Message :</td>
<td><textarea rows="3" cols="15" name="message" id="message" >
</textarea></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table> 

Step 4:

Now create "sendemailsuccess.jsp"  jsp file under WebContent folder. This jsp file used for displays message after send email. The code of  "sendemailbox.jsp"  given below as:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send email to selected dropdown user </title>
</head>
<body>
<b >Email has been send successfully.</b>
</body>
</html>

Step 5 :

Now open "web.xml" file and modify as :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" 
version="2.5">
<display-name>sendmail_fromdropdown</display-name>
<welcome-file-list> 
<welcome-file>index.jsp</welcome-file> 
</welcome-file-list>
<servlet>
<description></description>
<display-name>SendEmailToUser</display-name>
<servlet-name>SendEmailToUser</servlet-name>
<servlet-class>net.roseindia.SendEmailToUser</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SendEmailToUser</servlet-name>
<url-pattern>/sendemail</url-pattern>
</servlet-mapping>
</web-app>

Step 6 :

Now download "mail-1.4.jar" jar file and paste under  "WebContent/WEB-INF/lib" directory .

Step 7 :

When run  this application on tomcat server the following output will displays as:

1119sendemailto_user2.gif

After selecting User from dropdown list the output will be as below :

 1119sendemailto_user3.gif

Now if you click on "Submit" button without enter any value in the input field, then error message will be displays as :

1119sendemailto_user4.gif

If you enter invalid email address then error message will displays as:

1119sendemailto_user5.gif

Similarly the error message will be displayed for the message input field if it remains blank. If you fill all the correct information in all the input fileds and then click on "Submit" button then the email will be successfully sent to a specified user that you select from the dropdown list. A message will display after sending an email successfully as :    

1119sendemailto_user6.gif

Download Code

Download example code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics