Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML
 
 
Search All Tutorials

 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 
EJB
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

J2EE Tutorial - Send Email From JSP & Servlet

                           

A simple html form('dbdemo.htm') which invokes dbdemo.jsp  follows:

dbdemo.htm

<html>

<body>

<form       method=post    action=dbdemo.jsp>

type the selectquery  here

          <input   type=text   size=60    name='text1'> <br>

          <input   type=submit>

</form>

</body>

</html>

dbdemo.jsp

    <html>

    <body>

    <%@page import="java.sql.*"  %>

           <%

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            String    url  = "jdbc:odbc:telephone";                   // an access database registered in odbc  

            Connection     con = DriverManager.getConnection(url);

            Statement         stm = con.createStatement();       //  container for sql  

            String                sql = request.getParameter('text1');   // sql

            ResultSet          rs   = stm.executeQuery ( sql);

            while(rs.next())

               {

                   out.println(rs.getString(1)+"<br>");      // name

                   out.println(rs.getString(2)+"<br>");     // telephone number

                   out.println("========");

               }

          %>

</body>

</html>

--------------------------------------------------------------------------------------------------------------------------

As for sending mail from webserver, using JavaMail API, the following code shows how the required data

such as 'from', 'to', 'subject' and 'message' are collected  by the servlet and then processed for sending the mail.

------------------------------------------------------------------------------------------------------------------

mailservlet.htm

<html>

<body>

<form                    method=post              action="http://localhost:8080/servlet/mailservlet">

                    sender            <input type=text name=text1><br>

                     Reciever        <input type=text name=text2><br>

                     Subject          <input type=text name=text3><br>

                    Message        <textarea name='area1' rows=5 cols=30>                  </textarea>

                                             <input     type=submit>

</form>

</body>

</html>

 mailservlet.java

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

import javax.mail.*;

import javax.mail.internet.*;   // important

import javax.mail.event.*;      // important

import java.net.*;

import java.util.*;

public class servletmail extends HttpServlet

{

    public  void doPost(HttpServletRequest request,HttpServletResponse response)

                                  throws ServletException, IOException

    {

        PrintWriter out=response.getWriter();

        response.setContentType("text/html");

        try

        {

           Properties props=new Properties();

           props.put("mail.smtp.host","localhost");   //  'localhost' for testing

   Session   session1  =  Session.getDefaultInstance(props,null);

           String s1 = request.getParameter("text1"); //sender (from)

           String s2 = request.getParameter("text2");

           String s3 = request.getParameter("text3");

           String s4 = request.getParameter("area1");

     Message message =new MimeMessage(session1);

      message.setFrom(new InternetAddress(s1));

      message.setRecipients

              (Message.RecipientType.TO,InternetAddress.parse(s2,false));

           message.setSubject(s3);

           message.setText(s4);        

           Transport.send(message);

           out.println("mail has been sent");

        }

        catch(Exception ex)

        {

           System.out.println("ERROR....."+ex);

        }

    }

}

 

 Using javamail requires that we provide classpath to mail.jar & activation.jar. These should have been already installed in our machine. Otherwise, we will not be able to compile the servlet.  For testing the servlet, we should have installed some mail server in our machine.  For compiling the servlet, we have to set classpath to c:\jsdk2.0\src (java servlet development kit).

 (We are using Tomcat server.  The TOMCAT server is a webserver especially created for executing servlets and JSP . It is a joint effort by SunMicroSystems  & Apache Foundation. Tomcat can be run on Apache server or independently. Tomcat will work in Windows platform also. The current version is Tomcat 4. Tomcat 5 is expected shortly).

 We can  move dbdemo.htm and dbdemo.jsp to :

    c:\tomcat\webapps\root   directory.

 In another dos window,

   c:\tomcat\bin>SET   TOMCAT_HOME=C:\TOMCAT

                          >SET  JAVA_HOME=C:\JDK1.3

                          >startup ( this will start the tomcat server in port 8080)

Start InternetExplorer and type the url as 'http://localhost:8080/dbdemo.htm. We will get the form. Type the sql and submit the form. We will get the resultset sent by the server. We need not compile the jsp file. It is automatically compiled at the server.

For running a servlet, copy the servlet's class file to: c:\tomcat\webapps\root\web-inf\classes  directory.

For javamail , we  have to copy mail.jar & activation.jar to classes folder.

copy the invoking html file to: c:\tomcat\webapps\root     directory.

In the browser type the URL as 'http://localhost:8080/mailservlet.htm'. Enter the required data and submit the form to the server. The mail will be sent as specified by us. That is as brief a tour as possible  of the first group of technologies in the J2EE basket. This is an essential foundation because , even when we use RMI/EJB , the correct practice is to invoke the RMI through a servlet. In the JSP example seen above, the code was exposed to the web-administarator. The better method is to encapsulate the code as a bean and invoke it. This way, only the class file will be seen by the server-administaror. The JSP page also will be easier to read and maintain.In  the following  example , we will adopt that method.

                           

Facing Programming Problem?
Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

0 comments so far (post your own) View All Comments Latest 10 Comments:

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Hot Web Programming Job

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2007. All rights reserved.