从html检索参数到java电子邮件文件

时间:2018-03-22 15:16:19

标签: java html email parameters

我正在创建一个联系表单,允许用户输入他们的信息,并将电子邮件发送到指定的指定电子邮件。我一直无法找到检索html文件的参数并将其附加到电子邮件组件。例如,我希望电子邮件的主题是人员姓名和来自联系表单消息的消息。

- 这是我的java代码

public class Main {

private static String USER_NAME = "cakesbyluckydemo";  
private static String PASSWORD = "cakedemo";
private static String RECIPIENT = "cakesbyluckydemo@gmail.com";

public static void main(String[] args) {
    String from = USER_NAME;
    String pass = PASSWORD;
    String[] to = { RECIPIENT }; 
    String subject = "Java send mail example";
    String body = "Welcome to JavaMail!";

    sendFromGMail(from, pass, to, subject, body);
}

private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
    Properties props = System.getProperties();
    String host = "smtp.gmail.com";
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", from);
    props.put("mail.smtp.password", pass);
    props.put("mail.smtp.port", "587");
    props.put("mail.smtp.auth", "true");

    Session session = Session.getDefaultInstance(props);
    MimeMessage message = new MimeMessage(session);

    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] toAddress = new InternetAddress[to.length];


        for( int i = 0; i < to.length; i++ ) {
            toAddress[i] = new InternetAddress(to[i]);
        }

        for( int i = 0; i < toAddress.length; i++) {
            message.addRecipient(Message.RecipientType.TO, toAddress[i]);
        }

        message.setSubject(subject);
        message.setText(body);
        Transport transport = session.getTransport("smtp");
        transport.connect(host, from, pass);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    }
    catch (AddressException ae) {
        ae.printStackTrace();
    }
    catch (MessagingException me) {
        me.printStackTrace();
    }
}

}

- 这是我的一些HTML代码

 <form>
    <div class="field">
      <label class="label">Name</label>
      <div class="control">
        <input class="input" type="text" placeholder="e.g Alex Smith">
      </div>
    </div>        
    <div class="field">
      <label class="label">Email</label>
      <div class="control">
        <input class="input" type="email" placeholder="e.g. alexsmith@gmail.com">
      </div>
    </div>

    <div class="field">
      <label class="label">Message</label>
      <div class="control">
        <textarea class="textarea" placeholder="Textarea"></textarea>
      </div>
    </div>
    <div class="field is-grouped">
      <div class="control">
        <button class="button is-link">Submit</button>
      </div>
    </div>
  </form>

2 个答案:

答案 0 :(得分:0)

您需要一个将处理表单提交的servlet。 在servlet中,您可以检索表单值并调用sendFromGMail方法。

答案 1 :(得分:0)

要从java Web应用程序发送电子邮件,您必须使用Servlet,以便您调用提交输入表单。

让我们看一个例子:
你的html输入表格就像:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Email Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
<form action="servlet/SendEmail" method="post">
    <div class="col-sm-4"></div>
    <div class="container col-sm-6">
    <div class="form-group">
      <label for="name">Name: </label>
      <input type="text" class="form-control" id="name" placeholder="Enter name" name="name">
    </div>
    <div class="form-group">
      <label for="email">Email:</label>
      <input type="email" class="form-control" id="email" placeholder="Enter email" name="email">
    </div>
    <div class="form-group">
        <label for="message">Message Body:</label>
        <label><textarea class="form-control" rows="5" cols="100" placeholder="Enter your message" name="message"></textarea></label>
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
    </div>
  </form>
</div>

</body>
</html>

将扩展servlet类的java类如下:

import java.io.*;  
import javax.servlet.ServletException;  
import javax.servlet.http.*; 
import java.util.Properties;    
import javax.mail.*;    
import javax.mail.internet.*; 

public class SendEmail extends HttpServlet {  
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  

response.setContentType("text/html");  
PrintWriter out = response.getWriter();  

String name=request.getParameter("name");  
String toEmails=request.getParameter("email");  
String message=request.getParameter("message");  

String subject = "Test email";

try{  
    System.out.println("Data: \n "+"Name: "+name+" email: "+toEmails+" message: "+message); 
    sendFromGMail("youremail@gmail.com", "yourPassword", toEmails, subject, message);
    out.print("Message sent successfully");    
}catch (Exception e2) {
    System.out.println(e2);
    out.print("Message cannot send! Check setting"); 
}  

out.close();  
}

public void sendFromGMail(final String from,final String password,String to,String sub,String msg){  
          //Get properties object    
          Properties props = new Properties();    
          props.put("mail.smtp.host", "smtp.gmail.com");    
          props.put("mail.smtp.socketFactory.port", "465");    
          props.put("mail.smtp.socketFactory.class",    
                    "javax.net.ssl.SSLSocketFactory");    
          props.put("mail.smtp.auth", "true");    
          props.put("mail.smtp.port", "465");    
          //get Session   
          Session session = Session.getDefaultInstance(props,    
           new javax.mail.Authenticator() {    
           @Override
           protected PasswordAuthentication getPasswordAuthentication() {    
           return new PasswordAuthentication(from,password);  
           }    
          });    
          //compose message    
          try {    
           MimeMessage message = new MimeMessage(session);    
           message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));    
           message.setSubject(sub);    
           message.setText(msg);    
           //send message  
           Transport.send(message);    
           System.out.println("message sent successfully");    
          } catch (MessagingException e) {throw new RuntimeException(e);}    

    }  

}  

你的web.xml文件将是:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>SendEmail</servlet-name>
        <servlet-class>com.notearena.emailwebapp.SendEmail</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>SendEmail</servlet-name>
        <url-pattern>/servlet/SendEmail</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

您可以在此处找到完整的示例: https://github.com/Md-MamunAbdulKayum/Email-java-web-app-/tree/master