开发者

Getting HTML Data in Java Program

开发者 https://www.devze.com 2023-04-11 22:18 出处:网络
I am trying to send Email from a Java program that I found here http://stackoverflow.com/questions/73580/how-do-i-send-an-smtp-message-from-java , This code works fine(with the hardcoded information),

I am trying to send Email from a Java program that I found here http://stackoverflow.com/questions/73580/how-do-i-send-an-smtp-message-from-java , This code works fine(with the hardcoded information), but I want to send the information from an HTML page that I created, It has From, To, Subject,Text inputs but I dont know how to send the values of these inputs from HTML page to this Java program.. Any help will be appreciated. Thanks

Here is my Form

<html>
<head>
<title>Send Email</title>

</head>
<body>
<h1 align="center">Email Sending Client</h1>
</tr></td>
<table width=30% align="center">

<form id=myform method="get" action="" onSubmit="return validate();">

<br>
<tr>
<td>
<b>From:</b>
</td>
<td>
<input type="text" name="email" id="email">
</td>
</tr>



<tr>
<td>
<b>To:</b>
</td>
<td>
<input type="text" name="to" id="to">
</td>
</tr>



<tr>
<td>
<b>Subject:</b>
</td>
<td>
<input type="text" name="sub" id="sub">
</td>
</tr>






<tr>
<td>
<b>Message:</b>
</td>
<td>
<p><textarea name="textarea" cols="16" rows="6"></textarea></p>
</td>
</tr>

<tr>
<td>
<br>
<input type=submit value="Send" align="center">
</td>
</tr>

</table>
</body>
</form>
</html>

Code for Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.smtp.*;

public class sendemail extends HttpServlet {


 public static void main(String args[]) throws Exception ,ServletException, IOException{

      HttpServletRequest request=null;
      HttpServletResponse response=null;
    // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWrite开发者_如何学JAVAr();
      String title = "Using GET Method to Read Form Data";


     String email= request.getParameter("email");  
     String to= request.getParameter("to");  
     String sub= request.getParameter("sub");
     String smtp= request.getParameter("smtp");
     String mess= request.getParameter("mess"); 


            Properties props = System.getProperties();
            props.put("mail.smtps.host","smtp.gmail.com");
            props.put("mail.smtps.auth","true");
            Session session = Session.getInstance(props, null);
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(email));;
            msg.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to, false));
            msg.setSubject(sub);

            msg.setText(mess);
            //msg.setHeader("X-Mailer", "Tov Are's program");
            msg.setSentDate(new Date());
            SMTPTransport t =
                (SMTPTransport)session.getTransport("smtp");
            t.connect(smtp, "mymail@gmail.com", "mypassword");
            t.sendMessage(msg, msg.getAllRecipients());
            System.out.println("Response: " + t.getLastServerResponse());
            t.close();
  }


<html>
<head>
<title>Send Email</title>

</head>
<body>
<h1 align="center">Email Sending Client</h1>
</tr></td>
<table width=30% align="center">

<form id=myform method="get" action="sendemail" onSubmit="return validate();">

Your html form code

</form>
</html>

sendemail.java inside com.zetcode package

package com.zetcode;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
public class sendemail extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
                                  HttpServletResponse response)
                   throws IOException, ServletException {

        final String err = "/error.jsp";
        final String succ = "/success.jsp";

        String from = request.getParameter("from");
        String to = request.getParameter("to");
        String subject = request.getParameter("subject");
        String message = request.getParameter("message");

        try {
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");
            Authenticator auth = new SMTPAuthenticator("username","password");
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress("name <"+from+">"));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            Transport.send(msg);

        } catch (AuthenticationFailedException ex) {
            request.setAttribute("ErrorMessage", "Authentication failed");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (AddressException ex) {
            request.setAttribute("ErrorMessage", "Wrong email address");

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);

        } catch (MessagingException ex) {
            request.setAttribute("ErrorMessage", ex.getMessage());

            RequestDispatcher dispatcher = request.getRequestDispatcher(err);
            dispatcher.forward(request, response);
        }
            RequestDispatcher dispatcher = request.getRequestDispatcher(succ);
            dispatcher.forward(request, response);

    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }
}

make two other pages error.jsp and success.jsp to redirect to the particular page to see whether email sent or not... this code works for me I hope..now you can do it..


You already have the jsp. Create a Servlet class and map it to the url pattern of your form action and implement the doPost() method inside the Servlet. You can get the values sent from the form using request.getParameter(paramName) within the servlet.

0

精彩评论

暂无评论...
验证码 换一张
取 消