JavaMail - java.net.ConnectException:连接超时:连接

时间:2014-11-15 19:29:30

标签: gmail javamail server

这是我的代码。虽然发送邮件应该很简单,但我遇到了下面提到的错误。我试过到处寻找,但没有结果。 提前谢谢!

import java.util.Properties;  
import javax.mail.*;  
import javax.mail.internet.*;  

public class SendMailBySite {  
 public static void main(String[] args) {  

 String to="abc@gmail.com";//change accordingly  

  //Get the session 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.starttls.enable", "true");
  props.put("mail.smtp.port", "465");  

  Session session = Session.getDefaultInstance(props,  
   new javax.mail.Authenticator() {  
   protected PasswordAuthentication getPasswordAuthentication() {  
   return new PasswordAuthentication("abc@gmail.com","********");//change accordingly  
   }  
  });  

  //compose message  
  try {  
   MimeMessage message = new MimeMessage(session);  
   message.setFrom(new InternetAddress("abc@gmail.com"));//change accordingly  
   message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
   message.setSubject("Hello");  
   message.setText("Testing.......");  

   //send message  
   Transport.send(message);  

   System.out.println("message sent successfully");  

  } catch (MessagingException e) {throw new RuntimeException(e);}  

 }  
}

这是遇到的错误:

  

java.net.ConnectException:连接超时:连接

     

at java.net.DualStackPlainSocketImpl.connect0(Native Method)

     

在   java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)

     

在   java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)

     

在   java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)

     

在   java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)

     

at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)

     

在java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)

     

在java.net.Socket.connect(Socket.java:579)

     

at org.apache.commons.net.SocketClient.connect(SocketClient.java:182)

     

at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)

     

at org.apache.commons.net.SocketClient.connect(SocketClient.java:296)

     

at ftpserver.FTPServer.main(FTPServer.java:25)

1 个答案:

答案 0 :(得分:2)

首先,修复所有这些common mistakes

然后阅读这些debugging tips for connection problems

您可能想要阅读这些tips for connecting to Gmail