1

I want to send email in jsp using html form for value to, from, subject, body etc. But this code works not correctly. Please help me. Thanks

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <link href="bootstrap.css" rel="stylesheet" type="text/css"/>
        <script src="bootstrap.js" type="text/javascript"></script>
        <link href="style.css" rel="stylesheet" type="text/css"/>
        <script src="jquery-3.1.1.js" type="text/javascript"></script>

    </head>
    <body style="background-color:lightgreen">
         <form class="form-group" style=" margin-right:200px; padding: 30px 0px 0 25px;  background-color:white">                     
             <p style="margin: -30px 0 10px  70px; font-size: 20px">Sending Email </p>
                <input type="email" class="form-control" placeholder="To" required name="to" style="width:300px" /><br />
                <input type="email" class="form-control" placeholder="From" required name="from" style="width:300px" /><br />
                <input type="text" class="form-control" placeholder="subject:" required name="subject" style="width:300px" /><br />
                <textarea placeholder="body" required name="body" cols="32" rows="7" style="border:1px gray solid;border-radius:5px;"></textarea><br />
                <input type="submit" value="send" name="btn"   style="width: 300px; height: 35px; border: 1px solid gainsboro; border-radius: 4px; background-color:limegreen; color: white"/><br /><br />
    <%
     String from = request.getParameter("from");
          String to = request.getParameter("to");
          String subject = request.getParameter("subject");
           String bod = request.getParameter("body");
      final String username = "muneeb";
      final String password = "******";
// Get system properties object
      String host = "smtp.gmail.com";

      Properties props = new Properties();
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.starttls.enable", "true");
      props.put("mail.smtp.host", host);
      props.put("mail.smtp.port", "587");

      // Get the Session object.
        Session session1 = Session.getInstance(props,
      new javax.mail.Authenticator() {
         protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
         }
      });

      try {
         // Create a default MimeMessage object.
         Message message = new MimeMessage(session1);

         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.setRecipients(Message.RecipientType.TO,
         InternetAddress.parse(to));

         // Set Subject: header field
         message.setSubject(subject);

         // Now set the actual message
         message.setText(bod);
         // Send message
         Transport.send(message);

         System.out.println("Sent message successfully....");

      } catch (MessagingException e) {
             System.out.println(" faild message....");

      }
%>
    </div>
        </div>
</body>
</html>

It shows this error:

org.apache.jasper.JasperException: An exception occurred processing JSP page /assignment3/send_email.jsp at line 132 129: Message message = new MimeMessage(session1); 130: 131: // Set From: header field of the header. 132: message.setFrom(new InternetAddress(from)); 133: 134: // Set To: header field of the header. 135: message.setRecipients(Message.RecipientType.TO, Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:481) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329) javax.servlet.http.HttpServlet.service(HttpServlet.java:742) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

Reporter
  • 3,897
  • 5
  • 33
  • 47
bhatti
  • 21
  • 3
  • It's hard to say what's wrong with a full stacktrace, but I would bet on a bad "FROM" so `InetAddress` constructor throws –  May 22 '17 at 11:37
  • I don't know what you try to to accomplish, but that scriptlet is executed BEFORE the user gets the page, no when they submit that form – Pablo Lozano May 22 '17 at 11:37
  • Avoid the use of scriptlets as much as possible. http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files?rq=1 – Nico Van Belle May 22 '17 at 11:46
  • @Coder ACJHP says "I think if you do this in Servlet it's better" ... I will remove the "I think" qualification and say _You **should** do this in a Servlet_. Writing directly in a JSP using the `<% ... %>` tags has been _deprecated for **ten years**_. @Maurice Perry is right, your code to send the message is running before the user even gets a chance to fill out the form. – Stephen P May 23 '17 at 01:00

2 Answers2

1

I think if you do this in Servlet it's better.

Look at there I will give you a basic example it will get the parameters from html form and work it in servlet like :

`@WebServlet("/Servlet")
    public class Servlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Servlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        RequestDispatcher requestDispatcher;

        String from = request.getParameter("sender");
        String password = request.getParameter("pass");
        String to = request.getParameter("receiver");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");

        Properties properties = System.getProperties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.port", "587");

        if (from.contains("hotmail")) {
            properties.put("mail.smtp.host", "smtp.live.com");

        } else if (from.contains("gmail")) {
            properties.put("mail.smtp.host", "smtp.gmail.com");

        } else if (from.contains("yahoo")) {
            properties.put("mail.smtp.host", "smtp.mail.yahoo.com");

        } else {
            out.println("<h2 style='color:red;'>Unknown domain name!!</h2><br>"
                    + "<p>Please use 'Yahoo or Gmail or Hotmail'</p>");
        }

        Session messageSession = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(from, password);
            }
        });

        try {
            MimeMessage mimeMessage = new MimeMessage(messageSession);
            mimeMessage.setFrom(new InternetAddress(from));
            mimeMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            mimeMessage.setSubject(subject);
            mimeMessage.setText(message);

            Transport.send(mimeMessage);
            requestDispatcher = request.getRequestDispatcher("index.html");
            requestDispatcher.forward(request, response);
            out.println("<h2 style='color:green;'>Message sended successfully.</h2><br>" + "<p>Welldone.</p>");

        } catch (MessagingException e) {
            requestDispatcher = request.getRequestDispatcher("index.html");
            out.println("<h2 style='color:red;'>Fatal Error!!</h2><br>" + "<p>" + e.getMessage() + "</p>");
        }

    }

}
`

And basic HTML form :

<body>
<h1 align="center">Send Email Form</h1>
<form class="cf" action="Servlet" method="post">
    <div align="center">
        <table>
            <tr>
                <td>From : </td><td><input type="email" name="sender" size="30px" class="input-email"
                    placeholder="Email address"></td>
            </tr>
            <tr>
                <td>Password : </td><td><input type="password" name="pass" size="30px" class="input-email"
                    placeholder="Sender Password"></td>
            </tr>
            <tr>
                <td>To : </td><td><input type="email" name="receiver" size="30px" class="input-email"
                    placeholder="Email address"></td>
            </tr>
            <tr>
                <td>Subject : </td><td><input type="text" name="subject" size="30px" class="input-email"
                    placeholder="Subject"></td>
            </tr>
            <tr>
                <td>Message : </td><td><textarea name="message" id="input-message"
                        class="text" placeholder="Message"></textarea></td>
            </tr>
            <tr>
                <td><input type="submit" value="SEND" class="button">
                </td>
                <td><input type="reset" value="CLEAR" class="button">
                </td>
            </tr>
        </table>
    </div>

</form>

I hope this help you.

Coder ACJHP
  • 1,940
  • 1
  • 20
  • 34
0

Your JSP will be executed to display the form, and it will try to send an email before the user has a chance to enter anything.

You'd be better off moving the java code in a servlet.

Maurice Perry
  • 9,261
  • 2
  • 12
  • 24