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 (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(""));                                                                  message.addRecipient(Message.RecipientType.To,new InternetAddress(""));
            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 : 


Following the names of files to be created:
  • Servlet java file which controls the request and response. It will invoke the send() method of class that we have created to send the email.
  • 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) :


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.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) :


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 = ""; //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("", "");

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



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


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

} catch (MessagingException e) {

3)web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="" xmlns="" xmlns:web="" xsi:schemaLocation="" id="WebApp_ID" version="3.0">
<display-name>Send Mail</display-name>

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" "">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Send Email</title>

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


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

Mouri Tech Pvt Ltd,


Popular posts from this blog

Email sending using Servlet