Thursday, December 27, 2012

Email Sending Application using Java Mail API with Servlet and JSP

It is very simple to send email with Java Servlet using the Java Mail API and Java Activation Framework. This API provides classes that can be used to send simple emails. Today we have scripted an Email Sending Application with Java Servlet and JSP. You simply need an Internet connection to send email using this simple Application.
If you are not working with any IDE (Eclipse or NetBeans) , then you need add JavaMail API and Java Activation Framework(JAF) library jar files in your Classpath. Both the jar files along with other files are included in the script download folder.




Those who work with IDE (Eclipse or NetBeans) you can simply create a Java Web Application, and copy-paste the index.html file into index.jsp file. Then create a new Java Servlet into Source Package, name it SendMail.java and replace its code with SendMail.java file of this Script. That's it you are good to go, use it to send emails.

This script is currently configured to send emails using GMAIL ID's only. To use other email address, you simply need to add SMTP addresses of the respective email service into SendMail.java servlet.

  index.jsp :  


<form action="SendMail" method="post">
<div>To : <input type="text" name="to" class="tbox" /></div>
<div>Subject : <input type="text" name="sub" class="tbox" /></div>
<div>Message : <textarea name="msg"></textarea></div>
<div>Your Email id : <input type="text" name="eid" class="tbox" /></div>
<div>Password : <input type="password" name="pass" class="tbox" /></div>
<div><input type="submit" value="Send Email" id="btn1"/></div>
</form>


  SendMail.java :  


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

public class SendMail extends HttpServlet {
@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

   /*Retrieve value from the text field using getParameter() 
   method on Request object. Otherwise you can set it directly 
      also if you are not using any interface */  

         final  String to=request.getParameter("to");
         final  String subject=request.getParameter("sub");
         final  String msg=request.getParameter("msg");
         final String user=request.getParameter("eid");
         final String pass=request.getParameter("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 coding. Change accordingly, if your email id is not an gmail id*/

     props.put("mail.smtp.host", "smtp.gmail.com");
     props.put("mail.smtp.port", "587"); //this is optional
     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);
   }
});
   
   /* 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(subject);
 message.setText(msg);

  /* Transport class is used to deliver the message to the recipients */ 

 Transport.send(message);
 out.println("
"+"Email Send succesfully.."+" ");        }catch(Exception e){ e.printStackTrace();out.println(e.getMessage());} finally {            
            out.close();
        }
    }
}


We hope you like this awesome script, do comment if you face any problem. And don't forget to share this amazing and simple application. We will come up with more JSP-servlet scripts in the future.


Developer :
Abhijit Singh
Java Developer and Freelancer


9 comments:

  1. Thanks for ur informations, am working in web developing companies, so it will be helpful info for my works.

    ReplyDelete
  2. in net beans 5.5.1 it shwng error as source 1.4 is not sufficient for annotations use source 5 or higher nw what i have to do please send me mail with d steps hw to connect 2 source 5 to my mail id lakshmid.111@gmail.com

    ReplyDelete
  3. in net beans 7.2 it shwng error for send mail as main method not there for SendMail what i need to kept in main method send me d code

    ReplyDelete
  4. i m working the code in websphere server
    the certificate chaining error is occured
    how tosolve this problem
    pls reply me

    ReplyDelete
  5. i am working in eclipse ide
    i am getting
    535 No SMTP server defined. Use real server address instead of 127.0.0.1 in your account.
    how to solve this pls reply me soon

    ReplyDelete
    Replies
    1. Seems you are pointing to localhost that doesn't have any SMTP server defined / running. Or may be some application on your system is preventing your mail server to work.

      Maybe your Firewall or Antivirus is doing this.

      Delete
  6. Thanks bro it's working in Netbeans 6.9
    Thank You very much

    ReplyDelete
  7. i'm using NetBeans 7.3.1... while running this code i got a error as

    type Status report

    message /EmailApp/SendMail

    description The requested resource is not available.

    ReplyDelete
  8. props.put("mail.smtp.host", "smtp.gmail.com");



    is showing error here

    ReplyDelete