Sending email in a Servlet

In this part of the JEE tutorials we will send an email using a servlet. To work with email, we use the Java Mail API.

We need to add the mail.jar dependency to our project.

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.7</version>
</dependency>

This is the Maven dependency for the Java Mail API.

In order to send an email, we need to have an access to a mail server. In this tutorial, we use Google's SMTP server. Note that over the time, Google has changed the settings to connect to its SMTP servers. In order for the example to work, we need to temporarily set the Allow less secure apps option, which can be set in https://myaccount.google.com.

Sending email

In the next example we fill in an HTML form. Clicking on the Submit button the email is sent. We use the Java Mail API. The example consists of five files. A CSS style file provides the look and feel for our JSP pages. The index.jsp is used to fill in the form and send the data to the servlet. The EmailServlet processes the data and tries to send the email to the recipient. If it succeeds, the servlet forwards to the success.jsp file. If not, we receive an error message in error.jsp file.

style.css
* { font-size: 12px; font-family: Verdana }

input, textarea { border: 1px solid #ccc }
textarea { text-align:left}
table { margin-top: 10% }

.error { margin-top: 10%; border: 1px dotted #db1f1f; width: 250px }
.msg { margin-top: 10%; border: 1px dotted #ccc; width: 250px }

This is a style sheet file. The .error class provides a style for the error message. It is a dotted red rectangle. The .msg class is used in the success.jsp file. It is a gray dotted rectangle.

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Sending email</title>
        <link rel="stylesheet" href="style.css" type="text/css">
    </head>
    <body>
    <center>
        <form action="EmailServlet">   
            <table>
                <tr>
                    <td>From</td>
                    <td><input type="text" name="from" required></td>
                </tr>
                <tr>
                <tr>
                    <td>To</td>
                    <td><input type="text" name="to" required></td>
                </tr>
                <tr>
                    <td>Subject</td>
                    <td><input type="text" name="subject" required></td>
                </tr>    
                <tr>
                    <td>Message</td>
                    <td><textarea cols="25" rows="8" name="message"></textarea></td>
                </tr>
                <tr>
                    <td>Login</td>
                    <td><input type="text" name="login" required></td>
                </tr>
                <tr>
                    <td>Password</td>
                    <td><input type="password" name="password" required></td>
                </tr>
            </table>
            <br>
            <input type="submit" value="submit">
        </form>
    </center>
</body>
</html>

This is the form for sending the email. There are also inputs for the Gmail's login and password.

Email Form
Figure: Email Form

The EmailServlet sends the data from the form to the destination email address.

EmailServlet.java
package com.zetcode;

import java.io.IOException;
import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.RequestDispatcher;
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(name = "EmailServlet", urlPatterns = {"/EmailServlet"})
public class EmailServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        final String err = "/error.jsp";
        final String succ = "/success.jsp";

        String from = request.getParameter("from");
        String to = request.getParameter("to");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");
        String login = request.getParameter("login");
        String password = request.getParameter("password");

        RequestDispatcher dispatcher = request.getRequestDispatcher(succ);

        try {
            Properties props = new Properties();            
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");
            
            Authenticator auth = new SMTPAuthenticator(login, password);

            Session session = Session.getInstance(props, auth);

            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {
            
            request.setAttribute("ErrorMessage", "Authentication failed");

            dispatcher = request.getRequestDispatcher(err);

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

            dispatcher = request.getRequestDispatcher(err);

        } catch (MessagingException ex) {
            request.setAttribute("ErrorMessage", ex.getMessage());

            dispatcher = request.getRequestDispatcher(err);
        }

        dispatcher.forward(request, response);
    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    @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);
    }
}

This is the servlet that tries to send the email.

String from = request.getParameter("from");
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String message = request.getParameter("message");
String login = request.getParameter("login");
String password = request.getParameter("password");

We get the necessary parameters from the request.

Properties props = new Properties();
props.setProperty("mail.host", "smtp.gmail.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");

The Properties class is used for configuration. Notice that we set the authentication property to true.

Authenticator auth = new SMTPAuthenticator(login, password);

We create a new Authenticator class to check the login and the password.

Session session = Session.getInstance(props, auth);

We create a new mail session. We provide the properties and the Authenticator.

MimeMessage msg = new MimeMessage(session);
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(msg);

Here we create a message. We set the text of the message, subject, sender and recipient email addresses. Finally, we send the email message.

} catch (AuthenticationFailedException ex) {
            
    request.setAttribute("ErrorMessage", "Authentication failed");

    dispatcher = request.getRequestDispatcher(err);
}

Many things might go wrong while sending an email. For example we might provide a wrong email address or the authentication fails. Here we react to an AuthenticationFailedException. If we receive such an exception, we set an ErrorMessage attribute to the request and forward to the error.jsp file. The ErrorMessage attribute will be used in the error.jsp file.

error.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Error</title>
      <link rel="stylesheet" href="style.css" type="text/css">
    </head>
    <body>
      <center>
        <div class="error">
          <h2>Error</h2>
            <p>
               Message: <%= request.getAttribute("ErrorMessage") %>    
            </p>
        </div>
      </center>
    </body>
</html>

This JSP file will be displayed when an error occurs. The ErrorMessage attribute, which was set in the servlet, is displayed.

success.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

<html>
  <head>
    <title>Message</title>
    <link rel="stylesheet" href="style.css" type="text/css">
  </head>
  <body>
    <center>
      <div class="msg">
        <h2>Message</h2>
          <p>
               Email sent
          </p>
      </div>
   </center>
  </body>
</html>

This is the JSP file which will be displaed if no errors occured.

In this chapter we have sent an email using a Java Servlet and the Java Mail API.