通过javamail api发送邮件

时间:2015-07-15 15:24:53

标签: jsp javamail netbeans-8

我正在使用Netbeans IDE 8.0.2,我想从JSP页面向我的gmail帐户发送电子邮件。我在我的库中包含了jar文件,如javax.mail.jar,activation.jar,smtp-1.5.4.jar,javax.mail-api-1.5.4.jar和mailapi-1.5.4。 我的JSP代码是:

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
      String result;
   // Recipient's email ID needs to be mentioned.
      String to = "ambc@gmail.com";

 // Sender's email ID needs to be mentioned
    String from = "saini@ifmail.com";

// Assuming you are sending email from localhost
   String host = "localhost";

// Get system properties object
  Properties properties = System.getProperties();

// Setup mail server
  properties.setProperty("mail.smtp.host", host);


// Get the default Session object.
  Session mailSession = Session.getDefaultInstance(properties);

  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("My first localhost mail!");
   //  Now set the actual message
       message.setText("this is my first mail. hope it works");
   // Send message
       Transport.send(message);
      result = "Sent message successfully....";
     }catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: unable to send message....";
     }
   %>
<html>
     <head>
        <title>Send Email using JSP</title>
    </head>
    <body>
        <center>
            <h1>Send Email using JSP</h1>
       </center>
     <p align="center">
        <% 
            out.println("Result: " + result + "\n");
        %>
      </p>
    </body>
 </html>

我总是收到错误消息:结果:错误:无法发送消息.... 提前感谢您的帮助和建议。

1 个答案:

答案 0 :(得分:0)

我认为您可能需要允许从第三方应用程序访问您的Gmail帐户。我以前遇到过这个问题。 要允许访问,请执行以下操作:

  1. 登录您的Gmail帐户并访问此页面https://accounts.google.com/DisplayUnlockCaptcha并点击按钮以允许访问。
  2. 访问此页面https://www.google.com/settings/security/lesssecureapps并启用对安全性较低的应用的访问权限。