Sending an E-Mail Using JSP in Java

Introduction

This article explains how to send an email using JSP in Java. The NetBeans IDE is used to create this app.

Sending an Email in JSP

In other words, the JavaMail API. This API is created in various ways, but in this article I'll show you a simple format by which you can easily develop your own mail API.

Our Mail API is based on the two protocols SMTP and MIME.

Let's start creating this app

We need to follow several steps in the NetBeans IDE.

Step 1

Open the NetBeans IDE.

NetBeans IDE

Step 2

Choose "Java web" -> "Web application" as in the following.

Java Web App

Step 3

Specify "JSPMailApp" as the project name as in the following.

JSPMailApp

Step 4

Select the Server and version wizard as in the following.

Server and Version

Step 5

Now delete the default "index.jsp" file and create a new "index.html" file with the following code.

This page is created to receive the values from the user, like mail-id, subject and message content that they want to send. Then we send these details to the "mailJSP.jsp" page to respond depending on them.

index.html

<!DOCTYPE html>

<html>

    <head>

        <title>Sending Mail Through JSP</title>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <meta name="viewport" content="width=device-width">

    </head>

    <body bgcolor="khaki">

        <form action="mailJSP.jsp">

            <table>

                <tr><td><b><font color="red">To:

                    </td>

                    <td><b><b><input type="text" name="mail" value="Enter sender mail-id"/><br/>

                    </td>

                </tr>

                <tr>

                    <td>

                        <b><font color="red">Subject:

                    </td>

                    <td>

                        <input type="text" name="sub" value="Enter Subject Line"><br/>

                    </td>

                </tr>

                <tr>

                    <td>

                        <b><font color="red">Message Text:

                    </td>

                    <td>

                        <textarea rows="12" cols="80" name="mess"></textarea><br/>

                    </td>

                </tr>

                <tr>

                    <td>

                        <input type="submit" value="Send">

                    </td>

                    <td>

                        <input type="reset" value="Reset">

                    </td>

                </tr>

            </table>

        </form>

    </body>

</html>

Step 6

Now create a new JSP page "mailJSP.jsp" and write the following code for it. In the comment line I'll provide you a short description of the use of each attribute.

mailJSP.jsp

<%@ page import="java.util.*,javax.mail.*"%>

<%@ page import="javax.mail.internet.*" %>

<%

    //Creating a result for getting status that messsage is delivered or not!

    String result;

    // Get recipient's email-ID, message & subject-line from index.html page

    final String to = request.getParameter("mail");

    final String subject = request.getParameter("sub");

    final String messg = request.getParameter("mess");

 

    // Sender's email ID and password needs to be mentioned

    final String from = "enter your gmail-id";

    final String pass = "enter your gmail-password";

 

    // Defining the gmail host

    String host = "smtp.gmail.com";

 

    // Creating Properties object

    Properties props = new Properties();

 

    // Defining properties

    props.put("mail.smtp.host", host);

    props.put("mail.transport.protocol", "smtp");

    props.put("mail.smtp.auth", "true");

    props.put("mail.smtp.starttls.enable", "true");

    props.put("mail.user", from);

    props.put("mail.password", pass);

    props.put("mail.port", "465");

 

    // Authorized the Session object.

    Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {

        @Override

        protected PasswordAuthentication getPasswordAuthentication() {

            return new PasswordAuthentication(from, pass);

        }

    });

 

    try {

        // Create a default MimeMessage object.

        MimeMessage message = new MimeMessage(mailSession);

        // Set From: header field of the header.

        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.

        message.addRecipient(Message.RecipientType.TO,

                new InternetAddress(to));

        // Set Subject: header field

        message.setSubject(subject);

        // Now set the actual message

        message.setText(messg);

        // Send message

        Transport.send(message);

        result = "Your mail sent successfully....";

    } catch (MessagingException mex) {

        mex.printStackTrace();

        result = "Error: unable to send mail....";

    }

%>

<title>Sending Mail in JSP</title>

<h1><center><font color="blue">Sending Mail Using JSP</font></h1>

<b><center><font color="red"><% out.println(result);%></b>

Note: You need to add two JAR files, named "mail.jar" and "activation.jar" to run this app. You can directly download this JAR file from the Oracle website.

Step 7

Now our project is ready to run.

Right-click on the "index.html" file and select "Run". The following interface will be generated.

Output

Step 8

Now provide the detail there as "mail-id", "subject-line" and "message-content" as in the following that I provided.

Providing Detail

Step 9

Click on the "send" button. The following message will be generated. If it's showing an error, in other words something is missing, then recheck your JSP code and try again else you will get the same message as in the following.

Showing Confirmation Message

Step 10

For confirmation of the mail go to the receive mail inbox (those mail-ids that you provide in the sending page) or go to your mail-id and check the sent mail items. As in the following.

Gmail (Vinay-Account)

Mail-Inbox

Summary

I have already written an article on JavaMailAPI using a servlet in Java, but when I create the same in JSP I encounter many problem and when I find a solution in Google I don't find a proper answer so with the help of my seniors and friends I created this app successfully. So since I encountered so many problems, I don't want you to suffer the same, so you can use this code and create your own Mail API in JSP. Thanks for reading.