Sending email in JAVA Servlet



  • There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible for sending emails.We will be using the JavaMail API that provides all the classes required for sending an email.
  • Use the SMTP server provided by the host provider e.g. my SMTP server is mail.javamail.com (or)
  • Use the SMTP Server provided by other companies e.g. Gmail etc.
  • For sending the email using JavaMail API, you need to load the two jar files: 
  1. java-mail.jar
  2. javax.activation.jar

SMTP ( Simple Mail Transfer Protocol ):

SMTP is an acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver the email. We can use Apache James server, Post cast server, claim server etc. as an SMTP server. But if we purchase the host space, an SMTP server is by default provided by the host provider. For example, my smut server is compartmentalization. If we use the SMTP server provided by the host provider, authentication is required for sending and receiving emails.


Steps to send email using JavaMail API:

There are following three steps to send email using JavaMail. They are as follows:
  1. Get the session object that stores all the information of host like host name, user name, password etc.
  2. Compose the message.
  3. Send the message.

 1) Get the session object:

  • The javax.mail.Session class provides two methods to get the object of the session, Session.getDefaultInstance() method and Session.getInstance() method. You can use any method to get the session object.
Example of getDefaultInstance() method :

         Properties properties = new Properties();  
         //fill all the information like host name etc.
    Session session = Session.getDefaultInstance(properties,null);
Example of getInstance() method :

         Properties properties = new Properties(); 




       Session session = Session.getInstance(properties,null);

2) Compose the message:
  • The javax.mail.Message class provides methods to compose the message. But it is an abstract class so it's subclass javax.mail.internet.The MimeMessage class is mostly used.
  • To create the message, you need to pass session object in MimeMessage class constructor. For example:
          MimeMessage message = new MimeMessage(session); 

  • Now message object has been created but to store information in this object MimeMessage class provides many methods. Let's see methods provided by the MimeMessage class

Example to compose the message :


            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress("abc@gmail.com"));                                                                  message.addRecipient(Message.RecipientType.To,new InternetAddress("xyz@gmail.com"));
            message.setHeader("Hi, everyone");
            message.setText("Hi, This mail is to inform you about the blog");

3) Send the message:
  • The javax.mail.Transport class provides the method to send the message.

Example to send the message : 

      Transport.send(message);


Following the names of files to be created:
  • Sent_Mail.java: Servlet java file which controls the request and response. It will invoke the send() method of Mail.java class that we have created to send the email.
  • Mail.java: A Java class that contains a method to send mail.
  • Web.xml: In that give servlet name and URL pattern.
  • Index.html: Will get the input from the user.



1) Sent_Mail.java :


package com.in;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Sent_Mail")
public class Sent_Mail extends HttpServlet
 {
    private static final long serialVersionUID = 1L;
      /**
       * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
       */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws         ServletException, IOException
 {

 }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws       ServletException, IOException 
  {
  
   PrintWriter out = response.getWriter();
   response.setContentType("application/json");
   response.setCharacterEncoding("utf-8");
   response.setStatus(response.SC_OK);
   response.addHeader("Access-Control-Allow-Origin", "*");
   String To = request.getParameter("To");
   String Text = request.getParameter("Text");
   String From = request.getParameter("From");
   Mail.send(To, Text, From);
   out.println("Mail sent successfully.......");

  }
}






























2) Mail.java :


package com.in;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Mail 
{

   public static void send(String to, String msg, String from)
    {

      final String MAIL_USERNAME = "abc123@gmail.com"; //change accordingly  


      final String MAIL_PASSWORD = "abc@1234";//change accordingly
  
     //Get the session object 

    // create an instance of Properties Class

      Properties props = new Properties();

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

   //Properties props = System.getProperties();

  //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);

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

//compose the message   

try {

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

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
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 */
// Send message  

Transport.send(message);

System.out.println("Sent message successfully........");

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






























3)web.xml :


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Send Mail</display-name>
<servlet>
<servlet-name>Sent_Mail</servlet-name>
<servlet-class>com.in.Sent_Mail</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Sent_Mail</servlet-name>
<url-pattern>/send_mail</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>




















4)index.html :


  • Right click on mouse and
  • Select “Run As”
  • Click on “Run on Server”.







<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send Email</title>
</head>
<body>

<form action="send_mail" method="Post">
  From : <input type="text" name="From"/><br/><br />
  To : <input type="text" name="To"/><br/><br />
  Enter Text : <textarea id="txtArea" rows="5" cols="40" name="Text"></textarea><br/><br/>
 <input type="submit" value="Submit"/>
</form>

</body>
</html>



  • Copy “URL” and paste in a browser and
  • Enter the valid e-mail id's “From” and “To” and
  • Write "Text"
  • Click on “Submit” button
  • You will see the output is “Mail sent successfully” on that page.





  • The message can be sent to the given valid email.

         EX: By assigning “To” address of a particular email, the text will be forwarded according to the email.
  • After the user received the email, the user can check it whether an email received the email regarding the text.






Conclusion: As shown, it is very useful to send an email using SMTP server in Java Servlet and you came to know about SMTP server.






    Further any queries contact me,


Thank you,

Ramakrishna Koppala,

krishna.rama107@gmail.com

Mouri Tech Pvt Ltd,










Comments

Popular posts from this blog

Email sending using Servlet