Friday, 19 April 2013

Send Email Using JSP




Here is an example to send an HTML email from your machine. Here it is assumed that your localhostis connected to the internet and capable enough to send an email.
This example is very similar to previous one, except here we are using setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%@ page import="java.sql.*,java.util.*,javax.activation.*"%>
<html>
<body bgcolor=lightblue>
<center>
<div style="color:navy;background-color:white;font:700 16pt arial">Forgot Password
</div>
<form action="forgotpassword.jsp" method="post">
Enter your email address
<input type=text name=email
   size=40>
<p>
<input type=submit value="Submit">
&nbsp;
<input type=button onclick="javascript:history.back()" value="Back">
</form>

<%
  String  email = request.getParameter("email");
  if ( email  == null ) return;

  Connection con = null;
  Statement  st  = null;
  ResultSet rs = null;
 try
 {
 // con = user.getConnection();
  st =  con.createStatement();
  rs = st.executeQuery("select uname, pwd from users where email = '"  + email + "'");

   if ( ! rs.next() )
  {
      out.println("Sorry! Email Address Not Found In Our Database. <p><a href=login.html>Login Page</a>");
      return;
   }

   String   un = rs.getString("uname");
   String   pwd = rs.getString("pwd");
   String body = "Dear Subscriber, <p>Use the following details to login.<p>Username : " + un + "<p>Password:"+ pwd + "<p>Webmaster,<br>javajobs.com";
   Properties props = System.getProperties();
  // Session msession = Session.getDefaultInstance(props, null);
 //  Message msg = new MimeMessage(msession);
  // msg.setFrom(new InternetAddress("webmaster"));
   //msg.setRecipient(Message.RecipientType.TO,
     // new InternetAddress(email));
  //msg.setDataHandler(
         //   new DataHandler(body,"text/html"));
  //msg.setSubject("Account Information");
   // send message
 // Transport.send(msg);Aryantech Pune
  out.println("Account details are sent to email address. Please use those details to login.<p> <a href=login.html>Login Page</a>");
  } // end of try
  catch ( Exception ex)
 {
     out.println("Sorry! Error : " + ex.getMessage() + "<p> <a href=login.html>Login Page</a>");
  }
 finally
{
    rs.close();
    st.close();
    con.close();
 }
%>
</body>
</html>
Aryantech Pune


No comments:

Post a Comment