How to send an E-Mail In JSP

Sending An Email Using JSP Code With Netbeans IDE

In this article I am going to describe how to send an e-mail in JSP using the NetBeans IDE(7.0). This article is divided into several Steps. 

Step 1 : Downloading and Registering Libraries in NetBeans IDE 7.0.

First of all, you need to download the latest version of Java Mail , as well as DJ Native Swing. After you download the libraries, you need to put them into the NetBeans Library Manager. I recommend you store all libraries in, for example, C:\Program Files\Java\libraries.


Step 2 : Creating a new JSP web project

In this step we select a new web project and click on next.

selet new web page.jpg

Step 3 : Name and Location

Giving a specific name and set a location for this web application and click on next button.

set name and location.jpg

Step 4 : Select server and setting

Select server GlassFish 3.1 and java EE 6 web application and also set the context path.

select serrver and setting it.jpg

Step 5 : Select Framework

There is no need to select any frame for this application and click on finish button.


Step 6 : Select New JSP File

Select a new JSP File in This Way. 

create new jsp file.jpg


Click on the finish button and code it with email receiving code in the following way.

<title>java mail </title>
<body bgcolor="green">
<%@ page import="java.util.*" %>
<%@ page import="javax.mail.*" %>
<%@ page import="javax.mail.internet.*" %>
<%@ page import="javax.activation.*" %>
String host = "localhost,";//your local host
String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String messageText = request.getParameter("body");
boolean sessionDebug = false;
Properties props = System.getProperties();
props.put("", host);
props.put("mail.transport.protocol", "smtp");
Session mailSession = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSentDate(new Date());
out.println("Mail was sent to " + to);
out.println(" from " + from);
out.println(" using host " + host + ".");



<body bgcolor="cyan">
<form action="index.jsp" method="post">
<table cellspacing="2" cellpadding="2" border="1">
<input type="text" name="to" size="30" maxlength="30">
<input type="text" name="from" size="30" maxlength="30">
<input type="text" name="subject" size="30" maxlength="30">
<td colspan="2">
<textarea cols="40" rows="10" name="body"></textarea>
<input type="submit" name="submit" value="Submit">
<input type="Reset">

Compile and Running The Application

After these step compile and run the application(shift+f6) and find the following output.





I hope that this application help you to understand in how to send an E-mail in JSP via NetBeans.