Open In App

Servlet – Sending Email

Last Updated : 31 Mar, 2022
Like Article

E-mail is considered the most secure, reliable, fast, and cheapest way of official communication over the internet. That’s the reason every second almost 2.7M emails are being sent. Therefore, your Web-Application may need an email service for many needs like – communication, Multi-Factor Authentication, etc.  Working with mailing service within servlet requires – SMTP server(local/remote) and the two following APIs.

  1. Java Mail API (JMA) – javax.mail.jar
  2. JavaBeans Activation Framework API (JAF) –  activation.jar


  • If you use the Gmail SMTP server, the Sign-in attempt can be blocked due to
    • 2-step verification is turned on,
    • Less secure app access is turned off.
  • You can either change the google account settings or use Sign-in with Google / Google generated App code.
  • Understanding mailing service protocols




Simple Mail Transfer Protocol is used to send a message from one mail server to another.                                                                


Post Office Protocol is used to retrieve messages from a mail server. This protocol transfers all messages from the mail server to the mail client.


Internet Message Access Protocol is used by web-based mail services such as Gmail and Yahoo. This protocol allows a web browser to read messages that are stored on the mail server. 


The Multipurpose Internet Mail Extension type specifies the type of content that can be sent as a message or attachment.

Understanding the Working of Email

Life-Cycle of Email

Steps to associate Java Mail API:

  1. Download the javax.mail.jar file.
  2. Copy the javax.mail.jar file to the application’s WEB-INF\lib directory.
  3. Add the javax.mail.jar file to the classpath for your application.

Steps to associate JavaBeans Activation Framework API:

  1. Download the ZIP file and extract the files.
  2. Copy the activation.jar file to the application’s WEB-INF\lib directory.
  3. Add the activation.jar file to the classpath for your application.

Note: The JavaBeans Activation Framework API is included with Java SE 6. As a result, if you’re using Java SE 6 or later, you don’t need to install this API.

Web-Application (Servlet) Structure:

Association of files in Servlet Web-Application

1] web.xml (configuration)


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"

2] index.html (Entering Details)


<!DOCTYPE html>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <form action="Email" method="post">
            <div align="center"> <h1>Enter the Credentials: </h1>
            <input type="hidden" name="action" value="add">
            <label for="sID">Sender ID :</label> <br>
            <input id="sID" type="text" name="id"> <br>
            <label for="sMail">Sender Email :</label> <br>
            <input id="sMail" type="email" name="emailSender"> <br>
            <label for="pw">Password :</label> <br>
            <input id="pw" type="password" name="password"> <br>
            <label for="rMail">Receiver Email :</label> <br>
            <input id="rMail" type="email" name="emailReceiver"> <br>
            <label for="sub">Subject :</label> <br>
            <input id="sub" type="text" name="subject"> <br>
            <label for="message">Message :</label> <br>
            <input id="message" type="text" name="message"><br>
            <input type="submit" value="Send">


Fill details in output of

3] (Servlet for handling details)


package mail.Servlet;
import static mail.Servlet.Mail.sendMail;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Email extends HttpServlet {
    protected void
    processRequest(HttpServletRequest request,
                   HttpServletResponse response)
        throws ServletException, IOException
        String id, sender, receiver, password, subject,
        // check if directed url
        String action = request.getParameter("action");
        String url = "/index.html";
        if (action == null) {
            // directed to email interface
            action = "join";
        if (action.equals("join")) {
            url = "/index.html";
        if (action.equals("add")) {
            // retrieve the entered credentials
            id = request.getParameter("id");
            sender = request.getParameter("emailSender");
                = request.getParameter("emailReceiver");
            password = request.getParameter("password");
            subject = request.getParameter("subject");
            message = request.getParameter("message");
            // get and set String value of email status
                sendMail(id, receiver, sender, subject,
                         message, true, password));
            // directed to page showing the status of email
            url = "/confirmation.jsp";
            .forward(request, response);
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
        processRequest(request, response);
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response)
        throws ServletException, IOException
        processRequest(request, response);
    // Returns a short description of the servlet.
    // @return a String containing servlet description
    @Override public String getServletInfo()
        return "Short description";


4] (Helper class for creating and sending mail)


Essential classes:





Contains Properties class that’s used to set the properties for the email session.


Contains Session, Message, Address, Transport, MessagingException classes to send messages.
javax.mail.internet Contains MimeMessage and InternetAddress classes to send Email messages over the internet.


Create and Send an Email Message:


Creating Mail Session:


  1. You have to create a mail session to create and send an email message.
  2. Before session creation, you need to create a Properties object containing properties (key-value pair) using the put(key, value) method that the session needs to send or receive mail.
  3. You at the least need to specify SMTP host property – use the ‘localhost’ keyword to specify SMTP server running on the same server as web-application. If you are using a remote SMTP server(e.g. Gmail server), use SMTPS protocol ( Secure connection and Authentication ).
  4. You can use other properties as well to configure mail sessions.
  5. Get Session object by wrapping Properties object into getDefaultInstance(Properties Object) method of Session class.

Common Properties


mail.transport.protocol Specifies the protocol that’s used for the session.

Specifies the host computer for the SMTP server.


Specifies the port that the SMTP server is using.


Specifies whether authentication is required to log in to the SMTP server.


Set to false to prevent an SSLException on an attempt to connect to the Gmail SMTP server.
// local SMTP server - Default 
Properties props = new Properties();
props.put("", "localhost");
Session session = Session.getDefaultInstance(props);
// local SMTP server - Configure
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("", "localhost");
props.put("mail.smtp.port", 25);
Session session = Session.getDefaultInstance(props);
// remote SMTP server
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("", "");
props.put("mail.smtps.port", 465);
Session session = Session.getDefaultInstance(props);


Creating Message:


  1. To create a message, you need to pass a Session object to the constructor of the MimeMessage class to create a MimeMessage object.
  2. You can set the subject, body, and addresses for the message.
  3. If the body is other than plain text, use the setContent() method to change the MIME type of message.
Message message = new MimeMessage(session);
// automatically sets to text/plain
message.setText("Test Successful"); 
message.setContent("<h1>Test Successful<h1>", "text/html");

Note: All of the Message methods used above throws javax.mail.MessagingException.

// add attachments within email

// create 1'st part of body
BodyPart bodyPart = new MimeBodyPart(); 
bodyPart.setText("Body Message");

Multipart multiPart = new MimeMultipart();
// wrap up 1'st part

// create 2'nd part of body
bodyPart = new MimeBodyPart(); 
DataSource source = new FileDataSource("Filename.txt");
bodyPart.setDataHandler(new DataHandler(source));

// wrap up 2'nd part.
// adds wrapped parts in message 


Addressing a message:


  1. Create an object of InternetAddress (Sub-class of Address class).
  2. The first argument specifies the email address.
  3. You can add a second argument to associate an ID or email address to be displayed.
  4. To set FROM address. use setFrom(Address add) method of the MimeMessage object.
  5. To set TO, CC (carbon copy), BCC  (blind carbon copy) address, use setRecipient(Type type, Address add) method of MimeMessage object.
  6. For multiple recipients, you can use setRecipients(Type type, Address[] add) method of the MimeMessage object.
// set sender
Address fromAdd = new InternetAddress("", "from ID");
// set recipient
Address toAdd = new InternetAddress("");
message.setRecipient(Message.RecipientType.TO, toAdd);
message.setRecipient(Message.RecipientType.CC, toAdd);
message.setRecipient(Message.RecipientType.BCC, toAdd);
// set recipients
message.setRecipients(Message.RecipientType.TO, new Address[]{new InternetAddress(""),new InternetAddress("")});
// add recipients
Address toAdd1 = new InternetAddress("");
message.addRecipient(Message.RecipientType.TO, toAdd1);

Note: When you send a carbon copy, the CC addresses appear in the message. When you send a blind carbon copy, the BCC address doesn’t appear in the message. If you use the two-argument constructor of InternetAddress, it throws the Exception.


Sending a message:


If the SMTP doesn’t require authentication, you can use the static send(Message msg) method of the Transport class to send a message.


  1. If the SMTP requires authentication, you can use the getTransport() method of the session object.
  2. Then you can use connect method – public void connect(String user, String password) , to specify credentials (username, password) to connect to the server.
  3. Use abstract void sendMessage(Message msg, Address[] addresses) method to send the message.
  4. You need to close the connection using the close() method if not used try-with-resources block.
Transport transport = session.getTransport();
transport.connect("email-id", "password");
transport.sendMessage("message", message.getAllRecipients());

Note: If the SMTP host is incorrect, the – static void send(Message msg) method throws SendFailedException.



package mail.Servlet;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Mail {
    public static String
    sendMail(String id, String to, String from,
             String subject, String body, boolean content,
             String password)
        String status = null;
        try {
            // acquire a secure SMTPs session
            Properties pros = new Properties();
            pros.put("mail.transport.protocol", "smtps");
            pros.put("", "");
            pros.put("mail.smtps.port", 465);
            pros.put("mail.smtps.auth", "true");
            pros.put("mail.smtps.quitwait", "false");
            Session session
                = Session.getDefaultInstance(pros);
            // Wrap a message in session
            Message message = new MimeMessage(session);
            if (content) {
                message.setContent(body, "text/html");
            else {
            // specify E-mail address of Sender and Receiver
            Address sender = new InternetAddress(from, id);
            Address receiver = new InternetAddress(to);
            // sending an E-mail
            try (Transport tt = session.getTransport()) {
                // acqruiring a connection to remote server
                tt.connect(from, password);
                status = "E-Mail Sent Successfully";
        catch (MessagingException e) {
            status = e.toString();
        catch (UnsupportedEncodingException e) {
            status = e.toString();
        // return the status of email
        return status;


5] confirmation.jsp (Check the status of email)



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <h3 align="center">Status of E-Mail : </h3>
        <h1 align="center">${requestScope.message}</h1>


Mail Status after life-cycle

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads