Java Mail App Using Servlet in Java

Introduction

This article explains how to create a Java Mail API. The NetBeans IDE is used for creating this application.

What is Java Mail API

This API is used to write, read and compose mails. This API provides a platform-independent and protocol-independent framework for sending and receiving mails. The javax.mail and javax.mail.activation packages contain the core classes of the Java Mail API.

Some uses

The following are some uses:

  • Used at the time of registering the user (sending notification such as thanks message)
  • Used when the user forgot their password; the password is then sent to the user's email-id
  • Used to send some important notification, update, etcetera.

 Some Protocols mainly used are

  • POP (Post Office Protocol).
  • NNTP (Network News Transfer Protocol).
  • SMTP (Simple Mail Transfer Protocol).
  • MIME (Multipurpose Internet Mail Extension Protocol).
  • etcetera

Note: In our application; we use the MIME and SMTP protocols.

Some core classes

The following are some core classes:

  • javax.mail.Folder
  • javax.mail.Message
  • javax.mail.Address
  • javax.mail.Store
  • javax.mail.Session
  • javax.mail.PasswordAuthentication
  • javax.mail.MimeMessages etcetera.

How to send email

This API provides many ways to send email, but you must have a SMTP server to send emails to. Use the simple GMail server or download any SMTP server manually.

How to send email

Use the following procedure to to send email:

  1. First get a session object
  2. Then compose message
  3. Finally, send the message

1. Get the Session Object

The javax.mail.Session class provides the following two method to get the object of a session.

  • Session.getInstance()
  • Session.getDefaultInstance()

2. Compose message

The javax.mail.Message class provides a method to compose the message. For this we need to pass the session object in the Mime interface.

Example

MimeMessage mssg=new MimeMessage(session);

3. Send the message

The javax.mail.Transport class provide methods to send the message.

  • static void send(Message mssg)
  • static void send(Message mssg, Address[] add)

Let's start creating our application using a servlet

For creating this application you first need to download the following JAR files and add to your project library.

  • activation.jar
  • mail.jar

Note: You can download the latest version of this JAR file directly from the Oracle Website.

Now you need to create following files:

  1. index.html file
  2. MailServlet.java file
  3. Mail.java file

1. index.html file

This file is necessary to provide an interface in which the user can provide their email-id, subject and message contents.

2. MailServlet.java file

This servlet file handles the request and provides the response to the user.

3. Mail.java file

This Java file contains the send method to send the email to the specifeid recipients.

Now to create this application we need to use the following procedure.

Step 1

Open the NetBeans IDE.

NetBeans IDE

Step 2

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

Java web application

Step 3

Provide your project name as "JavaMailAPP" as in the following.

JavaMailAPP

Step 4

Choose the Server and Java version wizard as in the following.

Server and version wizard

Step 5

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

index.html

<!DOCTYPE html>

<html>

    <head>

        <title>TODO supply a title</title>

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

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

    </head>

    <body bgcolor="pink">

        <form action="MailServlet">

            <table>

                <tr>

                    <td>To:</td>

                    <td><input type="text" name="mail"/><br/></td>

                </tr>

                <tr>

                    <td>Subject:</td>

                    <td><input type="text" name="subject"><br/></td>

                </tr>

                <tr>

                    <td>Message Text:</td>

                    <td><textarea rows="12" cols="80" name="message"></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 servlet named "MailServlet" and write the following code there.

MailServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

 

public class MailServlet extends HttpServlet {

 

    @Override

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

 

        String m = request.getParameter("mail");

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

        String messg = request.getParameter("message");

 

        SendMail.send(m, submessg);

        out.print("Your Mail has been sent successfully");

        out.close();

    }

}

Step 7

Create a Java file named "Mail" with the following code.

SendMail.java

import java.util.Properties;

import javax.mail.*;

import javax.mail.internet.*;

 

public class SendMail {

 

    public static void send(String m, String sub, String messg) {

 

        final String user = "enter your gmail id here";

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

 

        Properties props = new Properties();

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

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

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

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

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

        props.put("mail.user", "enter your gmail id");

        props.put("mail.password", "enter your gmail-password");

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

 

        Session session = Session.getDefaultInstance(props,

                new javax.mail.Authenticator() {

                    @Override

                    protected PasswordAuthentication getPasswordAuthentication() {

                        return new PasswordAuthentication(user, pass);

                    }

                });

 

        try {

            MimeMessage message = new MimeMessage(session);

            message.setFrom(new InternetAddress(user));

            message.addRecipient(Message.RecipientType.TO, new InternetAddress(m));

            message.setSubject(sub);

            message.setText(messg);

 

            Transport.send(message);

 

            System.out.println("Done");

 

        } catch (MessagingException e) {

            throw new RuntimeException(e);

        }

 

    }

}

Step 8

Check your "web.xml" file that the code is the same as the following.

web.xml

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

<web-app version="3.0" 

xmlns="http://java.sun.com/xml/ns/javaee" 

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>MailServlet</servlet-name>

    <servlet-class>MailServlet</servlet-class>

  </servlet>

 

  <servlet-mapping>

    <servlet-name>MailServlet</servlet-name>

    <url-pattern>/MailServlet</url-pattern>

  </servlet-mapping>

  <welcome-file-list>

    <welcome-file>index.html</welcome-file>

  </welcome-file-list>

</web-app>

Note:

For running this application first make some changes in your Gmail account.

Go to your Gmail account then select "Settings" -> "Enable popup".

Step 9

Now your project is ready to run.

Right-click on the Project menu and choose "Run". The following shows the output.

Output

Step 10

Now fill in the details as email-id, subject, and message content as shown below.

Filling Detail

Step 11

After filling in the details, click on the "send" button; the following message will be generated by the servlet.

Confirmation Message

Note:

If you get the same message then that means your message has been successfully sent, if any error is thrown then check the SMTP setting.

Step 12

If you want to check the mail then go to the mail-id you sent the mail to. I will assume you see the mail in your mail-box as below.

Gmail account


Similar Articles