Send email in servlet using gmail


To send an email using your a Servlet is simple enough but to start with you should have JavaMail API and Java Activation Framework (JAF) installed on your machine.
You need to add mail.jar and activation.jar files in your CLASSPATH.

Sending email

 We use the Java Mail API. In order to succeed sending an email, we must have a gmail account. We use the Google's smtp server to forward the email. So in the form, we must provide the login and the password of our gmail account. The example consists of five files. A css style file provides the look and feel for our jsp pages. The mail.html is used to fill in the form and send the data to the servlet. The EmailServlet processes the data and tries to send the email to the recipient. If it succeeds, the servlet forwards to the success.jsp file. If not, we receive an error message in error.jsp file.

style.css

body { width:1000px; border:0px; margin:0px auto; padding:0px; }
wrapper { margin:auto; width:1000px; }

.button { text-decoration:none; padding:8px; font:bold 12px Georgia,serif; color:white; 
background-color:rgb(0,130,130); border-color:rgb(0,130,130); }
.button:hover { text-decoration:none; padding:8px; font:bold 12px Georgia,serif; color:rgb(0,130,130);
background-color:white; border-color:rgb(0,130,130); }

fieldset { border-color:rgb(0,130,130); }
input:focus { background-color:yellow; }

mail.html

<html><head>
<title>Sending email</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head><body>

<div class="wrapper">
<fieldset style="padding:0px 10px 10px 10px; ">
<legend> Mail System </legend>

<form action="EmailServlet" method="post">  
<table> <tr> <td>From</td>
<td><input type="text" name="from"  size="60"></td>
</tr> <tr>
<td>To</td>
<td><input type="text" name="to"  size="60"></td>
</tr> <tr>
<td>Subject</td>
<td><input type="text" name="subject"  size="60"></td>
</tr> <tr>
<td>Message</td>
<td><textarea rows="10" cols="70" name="message"></textarea></td>
</tr> <tr>
<td>Login</td>
<td><input type="text" name="login" size="60"></td>
</tr> <tr>
<td>Password</td>
<td><input type="password" name="password" size="60"></td>
</tr> <tr>
<td><input type="submit" value="SUBMIT" class="button"></td>
<td><input type="reset" value="RESET" class="button"></td>
</tr> </table>
</form> </fieldset> </div>
</body> </html>

EmailServlet.java

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.*;

public class EmailServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
                   throws IOException, ServletException {
        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;
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
                   throws ServletException, IOException {
        processRequest(request, response);
    }
}  


Error.jsp

<html> <head>
<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>

Success.jsp

<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>


Enjoy...............

0 comments :