2016-07-27 102 views
6

這是應用程序的代碼。我一直在嘗試使用eclipse IDE來運行它。我還添加了所有必需的java郵件jar文件,即 dsn.jar,imap.jar,mailapi.jar,pop3.jar,smtp.jar,mail.jar。 但它給出了以下錯誤Could not connect to SMTP host: smtp.gmail.com, port: 587無法連接到SMTP主機:smtp.gmail.com,端口:587;嵌套異常是:java.net.ConnectException:連接超時:連接

沒有防火牆阻止訪問,因爲在ping smtp.gmail.com時收到回覆。 我甚至嘗試了這種方式:

javax.mail.MessagingException的:無法連接到SMTP主機: smtp.gmail.com,端口:587; 嵌套的異常是: java.net.ConnectException:連接超時:連接 at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972) at com.sun.mail.smtp.SMTPTransport.protocolConnect (SMTPTransport.java:642) at javax.mail.Service.connect(Service.java:317) at javax.mail.Service.connect(Service.java:176) at javax.mail.Service.connect(Service的.java:125) 在javax.mail.Transport.send0(Transport.java:194) 在javax.mail.Transport.send(Transport.java:124) 在PlainTextEmailSender.sendPlainTextEmail(PlainTextEmailSender.java:50) 在PlainTextEmailSender.main(PlainTextEmailSender.java:73) 導致:java.net.ConnectException:連接超時:連接 在java.net.DualStackPlainSocketImpl.connect0(本地方法) 在java.net.DualStackPlainSocketImpl.socketConnect(未知源) 在java.net.AbstractPlainSocketImpl.doConnect (未知來源) 在java.net.AbstractPlainSocketImpl.connectToAddress(未知來源) 在java.net.AbstractPlainSocketImpl.connect(未知來源) 在java.net.PlainSocketImpl.connect(未知來源) 在java.net.SocksSocketImpl (Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java: 319) 在com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233) 在com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)

package net.codejava.mail; 

    import java.util.Date; 
    import java.util.Properties; 

    import javax.mail.Authenticator; 
    import javax.mail.Message; 
    import javax.mail.MessagingException; 
    import javax.mail.PasswordAuthentication; 
    import javax.mail.Session; 
    import javax.mail.Transport; 
    import javax.mail.internet.AddressException; 
    import javax.mail.internet.InternetAddress; 
    import javax.mail.internet.MimeMessage; 

    public class PlainTextEmailSender { 

     public void sendPlainTextEmail(String host, String port, 
       final String userName, final String password, String toAddress, 
       String subject, String message) throws AddressException, 
       MessagingException { 

      // sets SMTP server properties 
      Properties properties = new Properties(); 
      properties.put("mail.smtp.host", host); 
      properties.put("mail.smtp.port", port); 
      properties.put("mail.smtp.auth", "true"); 
      properties.put("mail.smtp.starttls.enable", "true"); 

      // creates a new session with an authenticator 
      Authenticator auth = new Authenticator() { 
       public PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(userName, password); 
       } 
      }; 

      Session session = Session.getInstance(properties, auth); 

      // creates a new e-mail message 
      Message msg = new MimeMessage(session); 

      msg.setFrom(new InternetAddress(userName)); 
      InternetAddress[] toAddresses = { new InternetAddress(toAddress) }; 
      msg.setRecipients(Message.RecipientType.TO, toAddresses); 
      msg.setSubject(subject); 
      msg.setSentDate(new Date()); 
      // set plain text message 
      msg.setText(message); 

      // sends the e-mail 
      Transport.send(msg); 

     } 

     /** 
     * Test the send e-mail method 
     * 
     */ 
     public static void main(String[] args) { 
      // SMTP server information 
      String host = "smtp.gmail.com"; 
      String port = "587"; 
      String mailFrom = "user_name"; 
      String password = "password"; 

      // outgoing message information 
      String mailTo = "email_address"; 
      String subject = "Hello my friend"; 
      String message = "Hi guy, Hope you are doing well. Duke."; 

      PlainTextEmailSender mailer = new PlainTextEmailSender(); 

      try { 
       mailer.sendPlainTextEmail(host, port, mailFrom, password, mailTo, 
         subject, message); 
       System.out.println("Email sent."); 
      } catch (Exception ex) { 
       System.out.println("Failed to sent email."); 
       ex.printStackTrace(); 
      } 
     } 
    } 
+0

不,我沒有嘗試連接使用telnet客戶端,但我用cmd來檢查ping響應是否發送到smtp.gmail.com的ping請求。它在那裏工作得很好。 –

+0

正如你所說,我已經爲異常提供了完整的堆棧跟蹤。如果你能幫助我,這將是一件好事。 –

+0

其實我想在我的項目中使用它,我想發送一個隨機生成的用戶ID和密碼到特定用戶的電子郵件ID。但是,這個郵件的東西不工作:/ –

回答

0

作爲我說過,你的代碼沒有問題。如果有什麼事情,只是做了一些測試,嘗試刪除驗證部分,看看是否能工作:

public void sendPlainTextEmail(String host, String port, 
      final String userName, final String password, String toAddress, 
      String subject, String message) throws AddressException, 
      MessagingException { 

     // sets SMTP server properties 
     Properties properties = new Properties(); 
     properties.put("mail.smtp.host", host); 
     properties.put("mail.smtp.port", port); 
     properties.put("mail.smtp.auth", "true"); 
     properties.put("mail.smtp.starttls.enable", "true"); 
// *** BEGIN CHANGE 
     properties.put("mail.smtp.user", userName); 

     // creates a new session, no Authenticator (will connect() later) 
     Session session = Session.getDefaultInstance(properties); 
// *** END CHANGE 

     // creates a new e-mail message 
     Message msg = new MimeMessage(session); 

     msg.setFrom(new InternetAddress(userName)); 
     InternetAddress[] toAddresses = { new InternetAddress(toAddress) }; 
     msg.setRecipients(Message.RecipientType.TO, toAddresses); 
     msg.setSubject(subject); 
     msg.setSentDate(new Date()); 
     // set plain text message 
     msg.setText(message); 

// *** BEGIN CHANGE 
     // sends the e-mail 
     Transport t = session.getTransport("smtp"); 
     t.connect(userName, password); 
     t.sendMessage(msg, msg.getAllRecipients()); 
     t.close(); 
// *** END CHANGE 

    } 

這就是我每天都使用從我的應用程序發送幾十封電子郵件的代碼,它是100 %保證工作 - 當然,只要smtp.gmail.com:587是可到達的。

+0

其中* JDK *版本,你使用?源代碼在java 8中工作正常,但一再使用jdk 7失敗。 – ArifMustafa

+0

我使用的是Java 8,但是即使在Java 6上,該代碼也應該可以工作。它幾乎與每個JavaMail教程都相同。你得到@ArifMustafa有什麼錯誤? – walen

+0

我不知道爲什麼不在Java 7上工作,這對我來說現在是一個很大的混亂。錯誤與承受的相同。 – ArifMustafa

0

電子郵件通過成功的Gmail使用JDK 7與設置下面Gmail

轉到Gmail設置>帳戶和導入>其他谷歌帳戶設置>登錄在&安全

  1. 兩步驟驗證:關
  2. 允許不夠安全的應用:ON
  3. 應用密碼:1個密碼(16個字符長),以後與此替換當前密碼。

使用以下Maven的依賴關係:

spring-core:4.2.2 
spring-beans:4.2.2 
spring-context:4.2.2 
spring-context-support:4.2.2 
spring-expression:4.2.2 
commons-logging:1.2 

<dependency> 
    <groupId>javax.mail</groupId> 
    <artifactId>mail</artifactId> 
    <version>1.4.7</version> 
</dependency> 

和我的源代碼是:

import org.springframework.mail.javamail.JavaMailSenderImpl; 
import org.springframework.mail.javamail.MimeMessageHelper; 

import javax.mail.MessagingException; 
import javax.mail.internet.MimeMessage; 
import javax.swing.JOptionPane; 
import java.util.List; 
import java.util.Properties; 

public class Email { 

    public final void prepareAndSendEmail(String htmlMessage, String toMailId) { 

     final OneMethod oneMethod = new OneMethod(); 
     final List<char[]> resourceList = oneMethod.getValidatorResource(); 

     //Spring Framework JavaMailSenderImplementation  
     JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); 
     mailSender.setHost("smtp.gmail.com"); 
     mailSender.setPort(465); 

     //setting username and password 
     mailSender.setUsername(String.valueOf(resourceList.get(0))); 
     mailSender.setPassword(String.valueOf(resourceList.get(1))); 

     //setting Spring JavaMailSenderImpl Properties 
     Properties mailProp = mailSender.getJavaMailProperties(); 
     mailProp.put("mail.transport.protocol", "smtp"); 
     mailProp.put("mail.smtp.auth", "true"); 
     mailProp.put("mail.smtp.starttls.enable", "true"); 
     mailProp.put("mail.smtp.starttls.required", "true"); 
     mailProp.put("mail.debug", "true"); 
     mailProp.put("mail.smtp.ssl.enable", "true"); 
     mailProp.put("mail.smtp.user", String.valueOf(resourceList.get(0))); 

     //preparing Multimedia Message and sending 
     MimeMessage mimeMessage = mailSender.createMimeMessage(); 
     try { 
      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); 
      helper.setTo(toMailId); 
      helper.setSubject("I achieved the Email with Java 7 and Spring"); 
      helper.setText(htmlMessage, true);//setting the html page and passing argument true for 'text/html' 

      //Checking the internet connection and therefore sending the email 
      if(OneMethod.isNetConnAvailable()) 
       mailSender.send(mimeMessage); 
      else 
       JOptionPane.showMessageDialog(null, "No Internet Connection Found..."); 
     } catch (MessagingException e) { 
      e.printStackTrace(); 
     } 

    } 

} 

希望這會幫助別人。

相關問題