sending email using servlet

Sending email through servlet using javax.mail api and  stmp protocol   :

In this example we will see how to send an email in Servlet application. We will be using the JavaMail API that provides all the classes required for sending an email. JavaMail API encapsulates two important packages javax.mail and javax.mail.internet. These packages provide classes that can be used to send and recieve simple emails. You simply need an Internet connection to send email using this simple Application.

Following are the names of Files to be created :

1-index.html will get the input from user
2-MailApp.java servlet file will control the request and response. It will invoke send() of SendMail class that we have created to send the mail.
3-SendMail.java, a java class that contains method to send mail.


NOTE: if you want to download the javax.mail api then click here


First we will make our view page


1>    Index.html:  
                    

  <form action="mail" method="post">
  To:<input type="text" name="to"  /><br/>
  Subject:<input type="text" name="subject"  /><br/>
  Message:<input type="text" name="message"  /><br/>
  Your Email id:<input type="text" name="user" ><br/>
  Password<input type="password" name="pass"   /><br/>
  <input type="submit" value="send" />
</form>





2>     Make a class and name it to MailApp.java:

 import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MailApp extends HttpServlet {
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        String to = request.getParameter("to");
        String subject = request.getParameter("subject");
        String message =  request.getParameter("message");
        String user = request.getParameter("user");
        String pass = request.getParameter("pass");
        SendMail sm = new SendMail();
        SendMail.send(to,subject, message, user, pass);
        out.println("Mail send successfully");
    }   
}
3> now make another class and  name it SendMail.java:

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

public class SendMail 
    public static void send(String to, String sub, 
                         String msg, final String user,final String pass)
    { 
     //create an instance of Properties Class   
     Properties props = new Properties();
     
     /* Specifies the IP address of your default mail server
             for e.g if you are using gmail server as an email sever
           you will pass smtp.gmail.com as value of mail.smtp host. 
           As shown here in the code. 
           Change accordingly, if your email id is not a gmail id
        */
     props.put("mail.smtp.host", "smtp.gmail.com");
     //below mentioned mail.smtp.port is optional
     props.put("mail.smtp.port", "587");           
     props.put("mail.smtp.auth", "true");
     props.put("mail.smtp.starttls.enable", "true");
     
     /* Pass Properties object(props) and Authenticator object   
           for authentication to Session instance 
        */

    Session session = Session.getInstance(props,new javax.mail.Authenticator()
    {
            protected PasswordAuthentication getPasswordAuthentication() 
            {
                     return new PasswordAuthentication(user,pass);
            }
   });
    
   try
   {

          /* Create an instance of MimeMessage, 
                it accept MIME types and headers 
             */

    MimeMessage message = new MimeMessage(session);
       message.setFrom(new InternetAddress(user));
       message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
       message.setSubject(sub);
       message.setText(msg);

       /* Transport class is used to deliver the message to the recipients */
       
       Transport.send(message);


    }
    catch(Exception e)
    {
           e.printStackTrace();
    }
  }  
}


4> now map all this in your web.xml file (make your web.xml   under the WEB-INF foler ):


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
    <servlet>
        <servlet-name>mail</servlet-name>
        <servlet-class>MailApp</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>mail</servlet-name>
        <url-pattern>/mail</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>




Now run the program on server and if everything goes right then you will see this page 



now tap in send button and check your email ...



if this not work go to this https://www.google.com/settings/security/lesssecureapps 
and turn it on after this it will run ..!!

Comments

Popular Posts

Image