Friday 26 October 2012

HOW TO SEND EMAIL USING JSP

Create a new java web project and create index.jsp page, Then copy the below code and paste in the index.jsp page.



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Pankaj Bhardwaj</title>
</head>
<body>
<table border="1" width="50%"  cellpadding="0" cellspacing="0">
  <tr>
  <td width="100%">
  <form method="POST" action="mail.jsp"> 
  <table border="1" width="100%" cellpadding="0" cellspacing="0">
  <h1>TEST</h1>
  <tr>
  <td width="50%"><b>To:</b></td>
  <td width="50%"><input type="text" name="to" size="30"></td>
  </tr>
  <tr>
  <td width="50%"><b>From:</b></td>
  <td width="50%"><input type="text" name="from" size="30"></td>
  </tr>
  <tr>
  <td width="50%"><b>Subject:</b></td>
  <td width="50%"><input type="text" name="subject" size="30"></td>
  </tr>
  <tr>
  <td width="50%"><b>Description:</b></td>
  <td width="50%"><textarea name="description" type="text" 
    cols="40" rows="15" size=100>
  </textarea>
  </td>
  </tr>
  <tr>
  <td><p><input type="submit" value="Send Mail" name="sendMail"></td>
  </tr>
  </table>
  </p>
  </form>
  </td>
  </tr>
</table>
</body>
</html>


Now, Create another jsp page naming mail.jsp and copy and paste the below code in this page.



<%@ page language="java" import="javax.naming.*,java.io.*,javax.mail.*,
javax.mail.internet.*,com.sun.mail.smtp.*"%>
<html>
<head> 
<title>Mail</title>
</head>
<body>
<%
try{
  Session mailSession = Session.getInstance(System.getProperties());
  Transport transport = new SMTPTransport(mailSession,new URLName("localhost"));
  transport.connect("localhost",8084,null,null);
  MimeMessage m = new MimeMessage(mailSession);
  m.setFrom(new InternetAddress(%><%request.getParameter("from")%><%));
  Address[] toAddr = new InternetAddress[] {
  new InternetAddress(%><%request.getParameter("to")%><%)
  };
  m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr );
  m.setSubject(%><%request.getParameter("subject")%><%);
  m.setSentDate(new java.util.Date());
  m.setContent(%><%request.getParameter("description")%><%, "text/plain");
  transport.sendMessage(m,m.getAllRecipients());
  transport.close();
  out.println("Thanks for sending mail!");
}
catch(Exception e){
  out.println(e.getMessage());
  e.printStackTrace();
}
%>
</body>
</html>


NOTE: you must add the activation.jar and mail.jar file in your libraries. Otherwise the code will not work properly.



1 comment:

  1. hi
    Could not connect to SMTP host: localhost, port: 8080, response: -1

    i run this coding in netbeans above indicate error display what can i do

    ReplyDelete