来自Java程序的电子邮件无效

时间:2015-04-22 13:41:41

标签: java email

我写了一个java程序,用于使用我公司的电子邮件服务器发送电子邮件。 下面的代码段:

      Properties props = System.getProperties();
      props.put("mail.smtps.host", "mail.xxx.com");
      props.put("mail.smtps.auth", "true");
      props.put("mail.smtps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtps.port", "888");
      props.put("mail.smtp.starttls.enable","true");
      Session session =
      Session.getInstance(props, null); Message msg = new
      MimeMessage(session); msg.setFrom(new
      InternetAddress("yyy@mydomain.com"));
      msg.setRecipients(Message.RecipientType.TO,
      InternetAddress.parse("yyy@mydomain.com", false));
      msg.setSubject("Good Morning " + System.currentTimeMillis());
      msg.setText("This is for Test"); 
      msg.setHeader("X-Mailer", "My program"); 
      msg.setSentDate(new Date()); 
      SMTPTransport t = (SMTPTransport) session.getTransport("smtps");
      t.connect("mail.xxx.com", "yyy@mydomain.com", "myPwd");
      t.sendMessage(msg, msg.getAllRecipients());
      System.out.println("Response: " + t.getLastServerResponse());
      t.close();

电子邮件功能无效。 得到以下错误:

Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: mail.xxx.com, port: 888;
  nested exception is:
    java.net.ConnectException: Connection refused: connect
    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:295)
    at javax.mail.Service.connect(Service.java:176)
    at cab.mail.Distribution.main(Distribution.java:50)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(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)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)
    ... 4 more

想知道导致问题的原因。 我用gmail服务器和我的个人gmail id测试了这段代码,它运行正常。 无法弄清楚我在这里失踪了什么。

2 个答案:

答案 0 :(得分:0)

根本原因:

Caused by: java.net.ConnectException: Connection refused: connect

确保您的应用程序可以访问端口mail.xxx.com上的邮件服务器888,并确保您的端口在防火墙处处于打开状态。

答案 1 :(得分:0)

默认情况下,某些防病毒软件(例如ViruScan)仅允许SMTP选择程序(如Outlook),其白名单不包含Java。检查您的防病毒设置。当然,还有另一个答案中建议的防火墙设置。