TechTutorial

Java Web Application JSP & Servelet Web Design Web development

How to send verification emails using java mail API, JSP, and Servlet?

Send Verification email in JSP and servlet using java mail API

In this tutorial, we will learn how to send an email with a verification code in JSP and servlet technology using Java Mail API. When you are here, I hope you have a good command of Java and the basic concept of the SMTP email server. And you already set up your programming environment. 

Before starting programming, we had some prerequisites to send the email. The first one is the Java Mail API jar and the second is the file. And if you are going to use Gmail, please Security from your account setting. 

If you download those two jar files and change your Gmail security, then you are ready to go next and follow the below step.

Or You can watch our video tutorial on our YouTube Channel. And don’t forget to subscribe and comment if you face any problems or errors.

Send email verification using java mail api

STEP-1: Project Setup

  • Create a new Web Application Project in your favorite IDE. 
  • Create a web.xml file in your WEB-INF folder.
  • Create index.html and verify.jsp in your project web app folder.
  • Create a new package in your src/main folder. You can provide any name for your package.
  • Add those two jar files to your project build path, just right-click your Libraries Folder and add the jar file. 

STEP-2: Web Page Design

Copy the below code and paste it to your index.html page. After pasting the code, please take care of the form action name and method name.

<html>
    <head>
        <title>User Email Verification</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            h1{
                text-align: center;
                color: blueviolet;
                padding-top: 30px;
            }
            form{
                width: 250px;
                height: 300px;
                padding: 20px;
                position: absolute;
                background-color: blueviolet;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                text-align: center;
            }
            input{
                width: 100%;
                display: inline-block;
                margin: 20px 0;
                font-size: 20px;
            }
            label{
                color: #fff;
                font-weight: 700;
                font-size: 20px;
            }
        </style>
    </head>
    <body>
        <h1>User Email Verification</h1>
        <form action="UserVerify" method="post">
            <label>User Name</label>
            <input type="text" name="username">
            <label>User Email</label>
            <input type="email" name="useremail">
            <input type="submit" value="Register">
        </form>
    </body>
</html>

STEP-3: User Bean Design

Now go back to your source packages folder and right-click your package, create a new java class, and name it User.java. This is our user model class and this class contains a few fields including username, email, and code. You can add more fields as you want. Then create a constructor, getter, setter, and toString method. The User.java class code is below. 

N.B: If you do copy-paste, please take care of the package name.

package newpackage;

public class User {
    String name;
    String email;
    String code;

    public User() {
    }

    public User(String name, String email, String code) {
        this.name = name;
        this.email = email;
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
}

STEP-4: User Bean Design 

Now create one more java class, just right-clicking your package and naming it SendEmail.java. This class will play the main role to generate verification codes and sending emails to the user email box. So this class is very important, and it will contain two methods, which are the getRandom and sendEmail methods with the User parameter. 

To generate the verification code we will use getRandom() method, which will generate a 6-digit fixed random number using the java Random function when this method will be called. 

And sendEmail method’s role is to send an email to the destination email, including some text messages and the verification code. To send an email you need the host email SMTP server address, port number, etc. You can get this, just search on Google. Here I used mail.com as my host email. For this class, the code is given below, just copy and paste it down.

package newpackage;

import java.util.Properties;
import java.util.Random;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
    //generate vrification code
    public String getRandom() {
        Random rnd = new Random();
        int number = rnd.nextInt(999999);
        return String.format("%06d", number);
    }

    //send email to the user email
    public boolean sendEmail(User user) {
        boolean test = false;

        String toEmail = user.getEmail();
        String fromEmail = "youremail@myself.com";
        String password = "youremailpassword";

        try {

            // your host email smtp server details
            Properties pr = new Properties();
            pr.setProperty("mail.smtp.host", "smtp.mail.com");
            pr.setProperty("mail.smtp.port", "587");
            pr.setProperty("mail.smtp.auth", "true");
            pr.setProperty("mail.smtp.starttls.enable", "true");
            pr.put("mail.smtp.socketFactory.port", "587");
            pr.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
 
            //get session to authenticate the host email address and password
            Session session = Session.getInstance(pr, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromEmail, password);
                }
            });

            //set email message details
            Message mess = new MimeMessage(session);

    		//set from email address
            mess.setFrom(new InternetAddress(fromEmail));
    		//set to email address or destination email address
            mess.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
    		
    		//set email subject
            mess.setSubject("User Email Verification");
            
    		//set message text
            mess.setText("Registered successfully.Please verify your account using this code: " + user.getCode());
            //send the message
            Transport.send(mess);
            
            test=true;
            
        } catch (Exception e) {
            e.printStackTrace();
        }

        return test;
    }
}

STEP-5: Setup User form Handler Servlet 

Now create a servlet, just right-clicking your package and name it UserVerify.java. Learn how to create servlet and servlet-mapping  In this servlet, we will handle user-submitted form data from the index.html page. We will use this servlet name in the index page form action name, and the method name will be the post method. Then fetch the form data one by one using the request.getParameter(“username”). Here, the username parameter name is the same as the input field name in the user form on the index page. Then create the instance object of the SendEmail.java class.

package newpackage;

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


public class UserVerify extends HttpServlet {

   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            //feth form value
           String name = request.getParameter("username");
           String email = request.getParameter("useremail");
           
      		//create instance object of the SendEmail Class
           SendEmail sm = new SendEmail();
      		//get the 6-digit code
           String code = sm.getRandom();
           
      		//craete new user using all information
           User user = new User(name,email,code);
           
           //call the send email method
           boolean test = sm.sendEmail(user);
           
      		//check if the email send successfully
           if(test){
               HttpSession session  = request.getSession();
               session.setAttribute("authcode", user);
               response.sendRedirect("verify.jsp");
           }else{
      		  out.println("Failed to send verification email");
      	   }
           
        }
    }

    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

}

STEP-6: Get the user verification code

Now, we already created a verify.jsp page in the web pages folder to get the user-submitted verification codeThis page contains a simple form to get the user verification code. 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Verify Page</title>
    </head>
    <body>
        <span>We already send a verification  code to your email.</span>
        
        <form action="VerifyCode" method="post">
            <input type="text" name="authcode" >
            <input type="submit" value="verify">
        </form>
    </body>
</html>

STEP-7: Verify the user-submitted code

Create another servlet to check that the submitted code is correct or not. If the code is correct, we will finish our registration process and perform other tasks. Else, we will show an error message. 

package newpackage;

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

public class VerifyCode extends HttpServlet {

   
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            
            HttpSession session = request.getSession();
            User user= (User) session.getAttribute("authcode");
            
            String code = request.getParameter("authcode");
            
            if(code.equals(user.getCode())){
                out.println("Verification Done");
            }else{
                out.println("Incorrect verification code");
            }
            
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

}

That’s all for this tutorial. I hope you followed all the processes as I explained. If you get any error, feel to comment. And if it is helpful please share it with your friends on Facebook, Twitter WhatsApp, etc.

30 thoughts on “How to send verification emails using java mail API, JSP, and Servlet?

  1. I was having the same issue

    Type Status Report

    Message The requested resource [/Testproject/UserVerify] is not available

    Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

    then I made a new servlet in source package with the same name UserVerify and click on the (add info to web.xml….) tab and click finish and then copy paste the code .It started running also change the smtp server properties if u r using gmail.

  2. SEVERE: Servlet.service() for servlet [newpackage.UserVerify] in context with path [/Email_Verification] threw exception [Servlet execution threw an exception] with root cause
    java.lang.ClassNotFoundException: javax.mail.Authenticator

    showing this error

  3. SEVERE [http-nio-8080-exec-70] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [VerifyCode] in context with path [/WebApplication2] threw exception
    java.lang.NullPointerException
    at newpackage.VerifyCode.processRequest(VerifyCode.java:23)
    at newpackage.VerifyCode.doPost(VerifyCode.java:37)

  4. javax.mail.MessagingException: Could not convert socket to TLS;
    nested exception is:
    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    help me

  5. i executed full code in netbeans 8.2
    after click register occured like this
    HTTP 404 not found
    type Status report

    messageNot Found

    descriptionThe requested resource is not available.

  6. I copy your source code but i am not getting output getting warning like this"Setting property 'source' to 'org.eclipse.jst.jee.server:EmailVerification' did not find a matching property.". pls give some solution

  7. can you help
    once admin register new user account while using their name,username and email address and it send one link to user email. user click the link it will come out one form to create their own password, and user once login their username and password it will go to the user page. can i know how want to do that.

    please help for me

Leave a Reply