How to send a html based email using a JSP page?

JSPJava 8Object Oriented ProgrammingProgramming

Here is an example to send an HTML 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.

This example is very similar to the previous one, except that here we are using the setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message.

Using this example, you can send as big an HTML content as you require.


<%@ 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.
      message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

      // Set Subject: header field
      message.setSubject("This is the Subject Line!");

      // Send the actual HTML message, as big as you like
      message.setContent("<h1>This is actual message</h1>", "text/html" );

      // Send message
      result = "Sent message successfully....";
   } catch (MessagingException mex) {
      result = "Error: unable to send message....";
      <title>Send HTML Email using JSP</title>
         <h1>Send Email using JSP</h1>
      <p align = "center">
            out.println("Result: " + result + "\n");
Published on 22-Mar-2019 11:18:12