Introduction
JSP stands for Java Server Pages. JSP is a server-side programming language that combines HTML, XML, Java Servlet, and JavaBeans technologies into one highly productive technology. It allows developers to develop reliable, high-performance, platform-independent web applications, and dynamic websites.
This article will learn how to send emails using JSP (Java Server Pages ). To send emails using JSP, we should have the Java Activation Framework (JAF) and the JavaMail API installed on our machine.
Refer to the following link:
- To download the latest version of JavaMail API.
- To download the latest version of Java Activation Framework (JAF).
We have the Java Activation Framework (JAF) and the JavaMail API installed on our computer. Let's get started with the article on how to send emails using JSP.
Send emails using JSP
In this section we will consider an example to send a simple email using JSP. For this, we need to add the activation.jar and the mail.jar files in our CLASSPATH. After adding all the required packages in the CLASSPATH let's make our SendMail.jsp file.
<%@ page import = "java.io.*,java.util.*,javax.mail.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ page import = "javax.mail.internet.*,javax.activation.*"%>
<%
String result;
// Recipient's email ID
String to = "abcd@codingninjas.com";
// Sender's email ID
String from = "mcmohd@codingninjas.com";
String host = "localhost";
// Get the system properties object
Properties properties = System.getProperties();
// Setup mail SMTP
properties.setProperty("mail.smtp.host", host);
// Get default Session object.
Session mailSession = Session.getDefaultInstance(properties);
try {
// Create a 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 !");
// Now set the actual message
message.setText("This is the actual message");
// Send message
Transport.send(message);
result = "Sent email successfully....";
} catch (MessagingException mex) {
mex.printStackTrace();
result = "Error: failed to send message....";
}
%>
<html>
<head>
<title>Send Emails using JSP</title>
</head>
<body>
<h1>Send Emails using JSP</h1>
<p > <% out.println("Result: " + result + "\n");%></p>
</body>
</html>
We implemented the logic for sending simple emails using JSP in the above code. Now, let's visit https://localhost:8080/sendmail.jsp to send a simple email to the given email id abcd@codingninjas.com. We will get a response like:
Output