How to send a simple text based email using a JSP page?

JSPJava 8Object Oriented ProgrammingProgramming

To send an email using a JSP, you should have the JavaMail API and the Java Activation Framework (JAF) installed on your machine.

  • You can download the latest version of JavaMail (Version 1.2) from the Java's standard website.

  • You can download the latest version of JavaBeans Activation Framework JAF (Version 1.0.2) from the Java's standard website.

Download and unzip these files, in the newly-created top-level directories. You will find a number of jar files for both the applications. You need to add the mail.jar and the activation.jar files in your CLASSPATH.

Send a Simple Email

Here is an example to send a simple email from your machine. It is assumed that your localhost is connected to the Internet and that it is capable enough to send an email. Make sure all the jar files from the Java Email API package and the JAF package are available in CLASSPATH.


 Live Demo

<%@ page import = "*,java.util.*,javax.mail.*"%>
<%@ page import = "javax.mail.internet.*,javax.activation.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
   String result;

   // Recipient's email ID needs to be mentioned.
   String to = "";

   // Sender's email ID needs to be mentioned
   String from = "";

   // Assuming you are sending email from localhost
   String host = "localhost";

   // Get system properties object
   Properties properties = System.getProperties();

   // Setup mail server
   properties.setProperty("", host);

   // Get the default Session object.
   Session mailSession = Session.getDefaultInstance(properties);

   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.
      new InternetAddress(to));
      // Set Subject: header field
      message.setSubject("This is the Subject Line!");

      // Now set the actual message
      message.setText("This is actual message");

      // Send message
      result = "Sent message successfully....";
   } catch (MessagingException mex) {
      result = "Error: unable to send message....";
      <title>Send Email using JSP</title>
         <h1>Send Email using JSP</h1>
      <p align = "center">
            out.println("Result: " + result + "
");          %>       </p>    </body> </html>

Let us now put the above code in SendEmail.jsp file and call this JSP using the URL  http"//localhost:8080/SendEmail.jsp. This will help send an email to the given email ID You will receive the following response −


Send Email using JSP
Result: Sent message successfully....
Updated on 30-Jul-2019 22:30:25