index.jsp---------------------------------------------------------------------------------------------------
In index.jsp, you need to have 5 text box for sender email address set by name="from", receiver email address set by name="to", subject set by name="subject", login set by name="login" and password set by name="password" in the index.jsp.It also requires one textarea for message set by name="message" in the index.jsp.These parameters are received by servlet file EmailServlet.java and process the required operation,i.e if no exceptions occurs then it will redirect to the success.jsp page else it will redirect to the error.jsp page.
-------------------------------------------------index.jsp-----------------------------------------------------
<%--
Document : index
Created on : 24 Jan, 2012, 3:52:40 PM
Author : ZISSAN
Email-id :ziszrcks@gmail.com
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Sending email</title>
</head>
<body>
<center>
<form action="EmailServlet" method="post">
<table>
<tr>
<td>From</td>
<td><input type="text" name="from"></td>
</tr>
<tr>
<tr>
<td>To</td>
<td><input type="text" name="to"></td>
</tr>
<tr>
<td>Subject</td>
<td><input type="text" name="subject"></td>
</tr>
<tr>
<td>Message</td>
<td><textarea cols="25" rows="8" name="message"></textarea></td>
</tr>
<tr>
<td>Login</td>
<td><input type="text" name="login"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
</table>
<input type="submit" value="submit">
</form>
<br><br>
</center>
</body>
</html>
------------------------------------------end of index.jsp--------------------------------------------------
After index.jsp, to compute the request or to handle the request we need a servlet file.This is done by writing the code in EmailServlet.java.For this right click the SourcePackage and select New-->Servlet-->
then set the class name as "EmailServlet.java" and set the package name as "email".Once this has been done you can see under SourcePackage, package name "email".Then you need to set this servlet and its url pattern in web.xml. For this right click the SendingEmail project node and select New-->Other-->Web-->
Standard Deployment Descriptor (web.xml).Once selected,set properties as default.This file you will find under the WEB-INF.
Remove the existing code and paste the following the code in web.xml
web.xml----------------------------------------------------------------------------------------------------
-----------------------------------------------web.xml-----------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>EmailServlet</servlet-name>
<servlet-class>email.EmailServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>EmailServlet</servlet-name>
<url-pattern>/EmailServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
-----------------------------------------end of web.xml----------------------------------------------------
Once servlet name, class and its url is set, then remove the existing code and paste the following the code in EmailServlet.java
EmailServlet.java-------------------------------------------------------------------------------------------
For this you need to have an account in gmail, therefore you need to set the following properties,i.e host name,port number,enabling authenticaton and enabling encryption.
-----------------------------------------EmailServlet.java--------------------------------------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package email;
import java.io.*;
import java.net.*;
import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* @author ZISSAN
*/
public class EmailServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
//PrintWriter out = response.getWriter();
final String err = "/error.jsp";
final String succ = "/success.jsp";
String from = request.getParameter("from");
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String message = request.getParameter("message");
String login = request.getParameter("login");
String password = request.getParameter("password");
try {
Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
Authenticator auth = new SMTPAuthenticator(login, password);
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(msg);
} catch (AuthenticationFailedException ex) {
request.setAttribute("ErrorMessage", "Authentication failed");
RequestDispatcher dispatcher = request.getRequestDispatcher(err);
dispatcher.forward(request, response);
} catch (AddressException ex) {
request.setAttribute("ErrorMessage", "Wrong email address");
RequestDispatcher dispatcher = request.getRequestDispatcher(err);
dispatcher.forward(request, response);
} catch (MessagingException ex) {
request.setAttribute("ErrorMessage", ex.getMessage());
RequestDispatcher dispatcher = request.getRequestDispatcher(err);
dispatcher.forward(request, response);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
dispatcher.forward(request, response);
}
private class SMTPAuthenticator extends Authenticator {
private PasswordAuthentication authentication;
public SMTPAuthenticator(String login, String password) {
authentication = new PasswordAuthentication(login, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
----------------------------------------end of EmailServlet.java-------------------------------------------
success.jsp -----------------------------------------------------------------------------------------------
Remove the existing code and paste the following the code
----------------------------------------------success.jsp--------------------------------------------------
<%--
Document : success
Created on : 24 Jan, 2012, 4:03:33 PM
Author : ZISSAN
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Message</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<center>
<div class="msg">
<h2>Message</h2>
<p>
Email sent
</p>
</div>
</center>
</body>
</html>
---------------------------------------end of success.jsp--------------------------------------------------
error.jsp --------------------------------------------------------------------------------------------------
Remove the existing code and paste the following the code
-----------------------------------------------error.jsp----------------------------------------------------
<%--
Document : error
Created on : 24 Jan, 2012, 4:02:53 PM
Author : ZISSAN
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Error</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<center>
<div class="error">
<h2>Error</h2>
<p>
Message: <%= request.getAttribute("ErrorMessage") %>
</p>
</div>
</center>
</body>
</html>
-------------------------------------end of error.jsp-------------------------------------------------------