03 May 2011

Send mail using Jsp and Servlet.

hello firends,

using this blog you can send mail using JSP and Servlets, follow the following steps to design this application


Send mail using Jsp and Servlet.
  1.    Create new web project using netbean. 
  2.       For this project following 5 labraries are requered.
a.       activation.jar
b.      mail.jar
c.       mailapi.jar
d.      pop3.jar
e.      smtp.jar
3.       After adding this library in project bellow code is copy and paste in index.jsp file.

index.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Java Mail</title>
    </head>
    <body>
        <form action="sendMail.jsp" method="POST">
            <table border="0" align="center" cellpadding="5">
                <tbody>
                    <thead><tr> <td colspan="3" align="center">
                    <b> Send Mail </b> </td> </tr> </thead>
                    <tr>
                        <td> To </td> <td> : </td>
                        <td> <input type="text" name="to" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Subject </td> <td> : </td>
                        <td> <input type="text" name="subject" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Message </td> <td> : </td>
                        <td> <textarea name="message" rows="8" cols="30">
                        </textarea></td>
                    </tr>
                    <tr>
                        <td colspan="3" align="center">
                        <input type="submit" value="Send Mail" />

                        <input type="reset" value="Reset" />
                        <td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>


Screen of index.jsp


sendMail.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Send Mail</title>
    </head>
    <body>
        <jsp:useBean id="mail" scope="session" class="jMail.Mail" />
        <jsp:setProperty name="mail" property="to" param="to" />
        <jsp:setProperty name="mail" property="from"  value="smaple@gmail.com" />

                <!-- Note:  value = add your email id hear -->

        <jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
        <jsp:setProperty name="mail" property="subject" param="subject" />
        <jsp:setProperty name="mail" property="message" param="message" />

        <%
String to = mail.getTo();
int result;
result = mail.sendMail();
if(result == 0){
    out.println(" Mail Successfully Sent to "+to);
}
else{
    out.println(" Mail NOT Sent to "+to);
}
       %>
    </body>
</html>






Java File: 

Mail.java


package jMail;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail {
    private String to;
    private String from;
    private String message;
    private String subject;
    private String smtpServ;


    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }
    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getSmtpServ() {
        return smtpServ;
    }
    public void setSmtpServ(String smtpServ) {
        this.smtpServ = smtpServ;
    }

public int sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp" );
              props.put("mail.smtp.starttls.enable","true" );
              props.put("mail.smtp.host",smtpServ);
              props.put("mail.smtp.auth", "true" );
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- Create a new message --
              Message msg = new MimeMessage(session);
              // -- Set the FROM and TO fields --
              msg.setFrom(new InternetAddress(from));
              msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
              msg.setSubject(subject);
              msg.setText(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Mr. XYZ" );
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK." );
              return 0;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return -1;
        }
  }

// Also include an inner class that is used for authentication purposes

private class SMTPAuthenticator extends javax.mail.Authenticator {
        @Override
  public PasswordAuthentication getPasswordAuthentication() {
         String username =  "sender@gmail.com";           // specify your email id here (sender's email id)
         String password = "password";                             // specify your password here
        return new PasswordAuthentication(username, password);
     }
  }
}




After complete the coding run the project.
                If any problem face then contact me at  “ xijay.ss@gmail.com “ and this project is also available at  www.project –source-code.com download and use.




hello firends,

using this blog you can send mail using JSP and Servlets, follow the following steps to design this application


Send mail using Jsp and Servlet.
  1.    Create new web project using netbean. 
  2.       For this project following 5 labraries are requered.
a.       activation.jar
b.      mail.jar
c.       mailapi.jar
d.      pop3.jar
e.      smtp.jar
3.       After adding this library in project bellow code is copy and paste in index.jsp file.

index.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Java Mail</title>
    </head>
    <body>
        <form action="sendMail.jsp" method="POST">
            <table border="0" align="center" cellpadding="5">
                <tbody>
                    <thead><tr> <td colspan="3" align="center">
                    <b> Send Mail </b> </td> </tr> </thead>
                    <tr>
                        <td> To </td> <td> : </td>
                        <td> <input type="text" name="to" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Subject </td> <td> : </td>
                        <td> <input type="text" name="subject" value="" /> </td>
                    </tr>
                    <tr>
                        <td> Message </td> <td> : </td>
                        <td> <textarea name="message" rows="8" cols="30">
                        </textarea></td>
                    </tr>
                    <tr>
                        <td colspan="3" align="center">
                        <input type="submit" value="Send Mail" />

                        <input type="reset" value="Reset" />
                        <td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>


Screen of index.jsp


sendMail.jsp
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Send Mail</title>
    </head>
    <body>
        <jsp:useBean id="mail" scope="session" class="jMail.Mail" />
        <jsp:setProperty name="mail" property="to" param="to" />
        <jsp:setProperty name="mail" property="from"  value="smaple@gmail.com" />

                <!-- Note:  value = add your email id hear -->

        <jsp:setProperty name="mail" property="smtpServ" value="smtp.gmail.com" />
        <jsp:setProperty name="mail" property="subject" param="subject" />
        <jsp:setProperty name="mail" property="message" param="message" />

        <%
String to = mail.getTo();
int result;
result = mail.sendMail();
if(result == 0){
    out.println(" Mail Successfully Sent to "+to);
}
else{
    out.println(" Mail NOT Sent to "+to);
}
       %>
    </body>
</html>






Java File: 

Mail.java


package jMail;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class Mail {
    private String to;
    private String from;
    private String message;
    private String subject;
    private String smtpServ;


    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }
    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getSmtpServ() {
        return smtpServ;
    }
    public void setSmtpServ(String smtpServ) {
        this.smtpServ = smtpServ;
    }

public int sendMail(){
        try
        {
            Properties props = System.getProperties();
              // -- Attaching to default Session, or we could start a new one --
              props.put("mail.transport.protocol", "smtp" );
              props.put("mail.smtp.starttls.enable","true" );
              props.put("mail.smtp.host",smtpServ);
              props.put("mail.smtp.auth", "true" );
              Authenticator auth = new SMTPAuthenticator();
              Session session = Session.getInstance(props, auth);
              // -- Create a new message --
              Message msg = new MimeMessage(session);
              // -- Set the FROM and TO fields --
              msg.setFrom(new InternetAddress(from));
              msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
              msg.setSubject(subject);
              msg.setText(message);
              // -- Set some other header information --
              msg.setHeader("MyMail", "Mr. XYZ" );
              msg.setSentDate(new Date());
              // -- Send the message --
              Transport.send(msg);
              System.out.println("Message sent to"+to+" OK." );
              return 0;
        }
        catch (Exception ex)
        {
          ex.printStackTrace();
          System.out.println("Exception "+ex);
          return -1;
        }
  }

// Also include an inner class that is used for authentication purposes

private class SMTPAuthenticator extends javax.mail.Authenticator {
        @Override
  public PasswordAuthentication getPasswordAuthentication() {
         String username =  "sender@gmail.com";           // specify your email id here (sender's email id)
         String password = "password";                             // specify your password here
        return new PasswordAuthentication(username, password);
     }
  }
}




After complete the coding run the project.
                If any problem face then contact me at  “ xijay.ss@gmail.com “ and this project is also available at  www.project –source-code.com download and use.




15 comments:

  1. after compiling the code we get an javax/mail/authentication , class not found error....

    solution :place the activation.jar and mail.jar in tomcat/common/lib

    ReplyDelete
  2. i am workiing on simpe jsp project and have no knowledge of netbeans..then how could i do this???

    ReplyDelete
  3. Hello,
    i tried this sample with Netbeans 6.9 but when i run the code, i have :

    1-error message:

    init:
    deps-module-jar:
    deps-ear-jar:
    deps-jar:
    library-inclusion-in-archive:
    library-inclusion-in-manifest:
    compile:
    compile-jsps:
    Starting GlassFish Server 3
    GlassFish Server 3 start failed.
    D:\NetBeansProjects\Mail2\nbproject\build-impl.xml:713: Deployment error:
    GlassFish Server 3 start failed.
    See the server log for details.
    BUILD FAILED (total time: 2 minutes 49 seconds)

    2- The Apache Derby server is started and ready to accept on port 1527

    3- Welcome to Felix
    2 janv. 2012 21:39:32 com.sun.enterprise.glassfish.bootstrap.ASMain main
    ================
    INFO: Launching GlassFish on Felix platform
    2 janv. 2012 21:39:32 com.sun.enterprise.glassfish.bootstrap.ASMainOSGi findDerbyClient
    INFO: Cannot find javadb client jar file, jdbc driver not available
    No config.properties found.



    I really don't get anything, what is happening here please?
    Thank you

    ReplyDelete
  4. super thanx!!!!!
    it works....

    ReplyDelete
  5. Thanks!... if any problem then send your mail ID to my mail (xijay.ss@gmail.com)

    ReplyDelete
  6. very very thank i will never forget you in the life

    ReplyDelete
  7. sir can you tell me if i want to send an attachment with this code what should i have to add more plzz tell d answer i will wait.

    ReplyDelete
  8. when i have run this code it does not shows error but it shows that mail Not sent to this person.I don't know what to do.can u help me??

    ReplyDelete
  9. not running following exception occure-->
    Exception javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect

    ReplyDelete
  10. plz help not running

    ReplyDelete
  11. Thank you sir,
    it works perfectly fine.

    One request to you sir can you send the code for
    Send mail using Jsp and Servlet (without using jsp:usebean)
    plz help me

    ReplyDelete
  12. please tell the logic and idea to create blog

    ReplyDelete

Thank you.