Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Servlet – Sending Email

  • Last Updated : 31 Mar, 2022

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

Pre-requisites: 

  • 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

   Protocols 

Description

     SMTP             

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

POP

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.

IMAP

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. 

MIME

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

<

ng>1] web.xml (configuration)

XML




<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
    <servlet>
        <servlet-name>Email</servlet-name>
        <servlet-class>mail.Servlet.Email</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Email</servlet-name>
        <url-pattern>/Email</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

2] index.html (Entering Details)

HTML




<!DOCTYPE html>
<html>
    <head>
        <title>GeeksforGeeks</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <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">
             
            </div>
        </form>
    </body>
</html>

Output:

Fill details in output of Mail.java

3] Email.java (Servlet for handling details)

Java




package mail.Servlet;
 
import static mail.Servlet.Mail.sendMail;
 
import java.io.IOException;
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,
            message;
 
        // 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");
            receiver
                = request.getParameter("emailReceiver");
            password = request.getParameter("password");
            subject = request.getParameter("subject");
            message = request.getParameter("message");
            // get and set String value of email status
            request.setAttribute(
                "message",
                sendMail(id, receiver, sender, subject,
                         message, true, password));
            // directed to page showing the status of email
            url = "/confirmation.jsp";
        }
 
        getServletContext()
            .getRequestDispatcher(url)
            .forward(request, response);
    }
 
    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
        throws ServletException, IOException
    {
        processRequest(request, response);
    }
 
    @Override
    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] Mail.java (Helper class for creating and sending mail)

 <

Essential classes:

 

Packages

Description

java.util

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

javax.mail

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

 

Create and Send an Email Message:

 

Cre

g 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

Description

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

mail.smtp.host

Specifies the host computer for the SMTP server.

mail.smtp.port

Specifies the port that the SMTP server is using.

mail.smtp.auth

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

mail.smtp.quitwait

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("mail.smtp.host", "localhost");
Session session = Session.getDefaultInstance(props);
// local SMTP server - Configure
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "localhost");
props.put("mail.smtp.port", 25);
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
// remote SMTP server
Properties props = new Properties();
props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", "smtp.gmail.com");
props.put("mail.smtps.port", 465);
props.put("mail.smtps.auth","true");
props.put("mail.smtps.quitwait","false");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);

 

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);
message.setSubject("Test");
// automatically sets to text/plain
message.setText("Test Successful"); 
message.setContent("<h1>Test Successful<h1>", "text/html");

Note: All of the Message methods used a

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
multiPart.addBodyPart(bodyPart); 

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

// wrap up 2'nd part.
multiPart.addBodyPart(bodyPart);
// adds wrapped parts in message 
message.setContent(multiPart); 

 

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@gmail.com", "from ID");
message.setFrom(fromAdd);
// set recipient
Address toAdd = new InternetAddress("to@gmail.com");
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("to1@gmail.com"),new InternetAddress("to2@gmail.com")});
 
// add recipients
Address toAdd1 = new InternetAddress("to@gmail.com");
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 java.io.UnsupportedEncoding 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.

 

Transport.send(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());
transport.close();

Note: If the SMTP host is incorrect, the – static void send(Messa

sg) method throws SendFailedException.

 

Java




package mail.Servlet;
 
import java.io.UnsupportedEncodingException;
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("mail.smtps.host", "smtp.gmail.com");
            pros.put("mail.smtps.port", 465);
            pros.put("mail.smtps.auth", "true");
            pros.put("mail.smtps.quitwait", "false");
            Session session
                = Session.getDefaultInstance(pros);
            session.setDebug(true);
            // Wrap a message in session
            Message message = new MimeMessage(session);
            message.setSubject(subject);
 
            if (content) {
                message.setContent(body, "text/html");
            }
            else {
                message.setText(body);
            }
            // specify E-mail address of Sender and Receiver
            Address sender = new InternetAddress(from, id);
            Address receiver = new InternetAddress(to);
            message.setFrom(sender);
            message.setRecipient(Message.RecipientType.TO,
                                 receiver);
            // sending an E-mail
            try (Transport tt = session.getTransport()) {
                // acqruiring a connection to remote server
                tt.connect(from, password);
                tt.sendMessage(message,
                               message.getAllRecipients());
                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)

 

HTML




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

Output:

Mail Status after life-cycle


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!