Core Java| JSP| Servlets| XML| EJB| JEE5| Web Services| J2ME| Glossary| Questions?

 

 

 

 

 

 

 

 

 

 

 

 

 

Search Tutorials:
 

Software Solutions and Services
 

 
  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.

                           

» View all related tutorials
Related Tags: java c j2ee ant language io tutorial experience ria this languages programmer student for ie program to ram presentation programmers

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

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.

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

Current Comments

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

Very Easy and good example

Posted by shashank on Friday, 01.30.09 @ 07:36am | #84325

You provide me with important settings, i mean configuration settings for tomcat. They works well. With the help of this content i could resolved all the problems, now im succeed in sending mails.
Thank you so much sir. Really nice job sir.

Posted by Naidu on Wednesday, 12.17.08 @ 13:16pm | #82889

how will retrieve the data, audio, videos, and etc..from data base using j2ee language.

Posted by raja on Wednesday, 12.10.08 @ 21:50pm | #82615

Respected Sir/Mam,
I am Asha Bhatt.I am working Onika Tech company before 1 week.Please give me the code of sending an email with connection & how to attech txt file in this code.My emailId is ashabhatt2707@gmail.com
Thank

Posted by Asha Bhatt on Friday, 09.26.08 @ 10:30am | #80712

how to set web logic server to work with java mail

when i am giving the localhost parameter in properties at runtime Exception is generated i.e.
send mail Exception

Please give me the answers and Exact code for the above problem

Posted by chandrakant on Saturday, 09.20.08 @ 13:35pm | #80564

Training Courses
Tell A Friend
Your Friend Name
Website Designing Services
 
Web Designing Packages From $150!
 
Website Designing Company Web Hosting
 
Website Designing Quotation
 
Search Tutorials:

 

 
 

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

Indian Software Development Company | iPhone Development Company in India | Flex Development Company in India | Java Training Delhi | Java Training at Noida |

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

Copyright © 2008. All rights reserved.