2015-01-11 54 views
0

這裏我想用Java和JSP發送郵件。使用JAVA和JSP發送郵件

的index.html

<html> 
<head> 
    <title>Sending Mail Through JSP</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <meta name="viewport" content="width=device-width"> 
</head> 
<body bgcolor="khaki"> 
    <form action="mailJSP.jsp"> 
     <table> 
      <tr><td><b><font color="red">To: 
       </td> 
       <td><b><b><input type="text" name="mail" value="Enter sender mail-id"/><br/> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        <b><font color="red">Subject: 
       </td> 
       <td> 
        <input type="text" name="sub" value="Enter Subject Line"><br/> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        <b><font color="red">Message Text: 
       </td> 
       <td> 
        <textarea rows="12" cols="80" name="mess"></textarea><br/> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        <input type="submit" value="Send"> 
       </td> 
       <td> 
        <input type="reset" value="Reset"> 
       </td> 
      </tr> 
     </table> 
    </form> 
</body></html> 

mailJSP.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%> 
<%@ page import="java.util.*,javax.mail.*"%> 
<%@ page import="javax.mail.internet.*" %> 
<% 
//Creating a result for getting status that messsage is delivered or not! 
String result; 
// Get recipient's email-ID, message & subject-line from index.html page 
final String to = request.getParameter("mail"); 
final String subject = request.getParameter("sub"); 
final String messg = request.getParameter("mess"); 

// Sender's email ID and password needs to be mentioned 
final String from = "my mail"; 
final String pass = "my pass"; 

// Defining the gmail host 
String host = "smtp.gmail.com"; 

// Creating Properties object 
Properties props = new Properties(); 

// Defining properties 
props.put("mail.smtp.host", host); 
props.put("mail.transport.protocol", "smtp"); 
props.put("mail.smtp.auth", "true"); 
props.put("mail.smtp.starttls.enable", "true"); 
props.put("mail.user", from); 
props.put("mail.password", pass); 
props.put("mail.port", "465"); 

// Authorized the Session object. 
Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() { 
    @Override 
    protected PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(from, pass); 
    } 
}); 

try { 
    // Create a default MimeMessage object. 
    MimeMessage message = new MimeMessage(mailSession); 
    // Set From: header field of the header. 
    message.setFrom(new InternetAddress(from)); 
    // Set To: header field of the header. 
    message.addRecipient(Message.RecipientType.TO, 
      new InternetAddress(to)); 
    // Set Subject: header field 
    message.setSubject(subject); 
    // Now set the actual message 
    message.setText(messg); 
    // Send message 
    Transport.send(message); 
    result = "Your mail sent successfully...."; 
} catch (MessagingException mex) { 
    mex.printStackTrace(); 
    result = "Error: unable to send mail...."; 
} 
%>`enter code here` 
<title>Sending Mail in JSP</title> 
<h1><center><font color="blue">Sending Mail Using JSP</font></h1> 
<b><center><font color="red"> 
<% out.println(result);%></b> 

我也想補充一點,我使用NetBeans IDE和Apache服務器,我已經添加的所有jar文件需要它,但仍然收到異常,並以「無法發送」結束。所以我很困惑我犯了什麼錯誤?

堆棧跟蹤:

Stacktrace: 
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103) 
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:366) 
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:476) 
org.apache.jasper.compiler.Compiler.compile(Compiler.java:378) 
org.apache.jasper.compiler.Compiler.compile(Compiler.java:353) 
org.apache.jasper.compiler.Compiler.compile(Compiler.java:340) 
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657) 
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357) 
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390) 
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334) 
javax.servlet.http.HttpServlet.service(HttpServlet.java:727) 
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 

異常

exception 

org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 74 in the jsp file: /mailJSP.jsp 
The local variable result may not have been initialized 
71: %> 
72: <title>Sending Mail in JSP</title> 
73: <h1><center><font color="blue">Sending Mail Using JSP</font></h1> 
74: <b><center><font color="red"><% out.println(result);%></b> 

希望它增加了更多的信息!

+0

mex.printStackTrace();的內容? –

+0

我把它用於打印抓到的異常!但是,一旦我運行的代碼沒有任何東西被捕獲在NetBeans輸出控制檯:( – SJith

+0

做的版本的jar文件很重要嗎? – SJith

回答

0

This可能會幫助你。爲我工作!另外,你應該已經展示了棧跟蹤。如果您的程序異常出錯,它有助於更​​好地理解。

+0

但Shubham,這裏應該是錯誤的,但我無法在這裏找到坑! – SJith

1
An error occurred at line: 74 in the jsp file: /mailJSP.jsp 

局部變量結果可能尚未初始化

String result = new String(); 

初始化變量

對於第二個例外

private final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; 
int port = 465; 
if ("smtp.gmail.com".equals(host)) { 
    props.setProperty("mail.smtp.socketFactory.class",SSL_FACTORY); 
    props.setProperty("mail.smtp.socketFactory.fallback","false"); 
    props.setProperty("mail.smtp.socketFactory.port",String.valueOf(port)); 
    } 
+0

現在新的異常彈出: 無法連接到SMTP主機:smtp.gmail.com,端口:25,那麼我該如何解決這個問題? – SJith

+0

編輯回覆 – ByHH

+1

[擺脫所有那些插座工廠的東西](http://www.oracle.com/technetwork/java/javamail/ faq/index.html#commonmistakes)並按照[連接到Gmail的這些說明](http://www.oracle.com/technetwork/java/javamail/faq/i ndex.html#的Gmail)。 –

0
props.put("mail.smtp.starttls.enable", "true"); 

您啓用TLS但實際上你使用ssl(端口465)。 試試這個:

Session mailSession = Session.getInstance(System.getProperties()); 
     Transport transport = new SMTPTransport(mailSession, new URLName("smtp.gmail.com")); 
     transport = mailSession.getTransport("smtps"); 
     transport.connect("smtp.gmail.com", 465, "[email protected]", "Your-Password-Here"); 
     MimeMessage m = new MimeMessage(mailSession); 
     m.setFrom(new InternetAddress("[email protected]")); 
     Address[] toAddr = new InternetAddress[]{ new InternetAddress("[email protected]@email.addr") }; 
     m.setRecipients(javax.mail.Message.RecipientType.TO, toAddr); 
     m.setSubject("set subject if you wish"); 
     m.setSentDate(new java.util.Date()); 
     String text = "BODY OF EMAIL"; 
     m.setContent(text, "text/plain"); 
     transport.sendMessage(m, m.getAllRecipients()); 
     transport.close(); 
     } catch (Exception e) { 
      out.println(e.getMessage() + " - " + e.toString()); 
      e.printStackTrace(); 

     }