Search This Blog

Friday, 6 December 2013

Sending email through JavaMail API in Servlet

The JavaMail API provides many classes that can be used to send email from java. The javax.mail and javax.mail.internet packages contains all the classes required for sending and receiving emails.
For better understanding of this example click steps for sending email from javamail api
For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar
download these jar files or go to the Oracle site to download the latest version.

Example of Sending email through JavaMail API in Servlet

Here is the simple example of sending email from servlet. For this example we are creating 3 files:
  • index.html file for input
  • SendMail.java , a servlet file for handling the request and providing the response to the user. It uses the send method of Mailer class to send the email.
  • Mailer.java , a java class that contains send method to send the emails to the mentioned recipient.

index.html
  1. <form action="servlet/SendMail">  
  2. To:<input type="text" name="to"/><br/>  
  3. Subject:<input type="text" name="subject"><br/>  
  4. Text:<textarea rows="10" cols="70" name="msg"></textarea><br/>  
  5. <input type="submit" value="send"/>  
  6. </form>  

SendMail.java
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3.   
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.http.HttpServlet;  
  6. import javax.servlet.http.HttpServletRequest;  
  7. import javax.servlet.http.HttpServletResponse;  
  8.   
  9.   
  10. public class SendMail extends HttpServlet {  
  11. public void doGet(HttpServletRequest request,  
  12.  HttpServletResponse response)  
  13.     throws ServletException, IOException {  
  14.   
  15.     response.setContentType("text/html");  
  16.     PrintWriter out = response.getWriter();  
  17.       
  18.     String to=request.getParameter("to");  
  19.     String subject=request.getParameter("subject");  
  20.     String msg=request.getParameter("msg");  
  21.           
  22.     Mailer.send(to, subject, msg);  
  23.     out.print("message has been sent successfully");  
  24.     out.close();  
  25.     }  
  26.   
  27. }  

Mailer.java
  1. import java.util.Properties;  
  2.   
  3. import javax.mail.*;  
  4. import javax.mail.internet.InternetAddress;  
  5. import javax.mail.internet.MimeMessage;  
  6.   
  7. public class Mailer {  
  8. public static void send(String to,String subject,String msg){  
  9.   
  10. final String user="sonoojaiswal@javatpoint.com";//change accordingly  
  11. final String pass="xxxxx";  
  12.   
  13. //1st step) Get the session object    
  14. Properties props = new Properties();  
  15. props.put("mail.smtp.host""mail.javatpoint.com");//change accordingly  
  16. props.put("mail.smtp.auth""true");  
  17.   
  18. Session session = Session.getDefaultInstance(props,  
  19.  new javax.mail.Authenticator() {  
  20.   protected PasswordAuthentication getPasswordAuthentication() {  
  21.    return new PasswordAuthentication(user,pass);  
  22.    }  
  23. });  
  24. //2nd step)compose message  
  25. try {  
  26.  MimeMessage message = new MimeMessage(session);  
  27.  message.setFrom(new InternetAddress(user));  
  28.  message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
  29.  message.setSubject(subject);  
  30.  message.setText(msg);  
  31.    
  32.  //3rd step)send message  
  33.  Transport.send(message);  
  34.   
  35.  System.out.println("Done");  
  36.   
  37.  } catch (MessagingException e) {  
  38.     throw new RuntimeException(e);  
  39.  }  
  40.       
  41. }  
  42. }  

Introduction Of Servlet

 Servlet ......


Servlet technology is used to create web application (resides at server side and generates dynamic web page).
Servet technology is robust and scalable as it uses the java language. Before Servlet, CGI (Common Gateway Interface) scripting language was used as a server-side programming language. But there were many disadvantages of this technology. We have discussed these disadvantages below.
There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.

What is a Servlet?

Servlet can be described in many ways, depending on the context.
  • Servlet is a technology i.e. used to create web application.
  • Servlet is an API that provides many interfaces and classes including documentations.
  • Servlet is an interface that must be implemented for creating any servlet.
  • Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.
  • Servlet is a web component that is deployed on the server to create dynamic web page.
servlet

Advantage of Servlet

advantage of servlet
There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lighweight, cost of communication between the threads are low. The basic benefits of servlet are as follows:
  1. better performance: because it creates a thread for each request not process.
  2. Portability: because it uses java language.
  3. Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage collection etc.
  4. Secure: because it uses java language..