0

我正在使用 Javamail API 尝试在我的 Java 代码中发送电子邮件。问题发生在特定线路上。

部分代码是:

 URLConnection c = u.openConnection();          
 c.setDoInput(false);                            
 c.setDoOutput(true);               
 c.connect(); 

错误发生在代码的 c.connect() 行。我得到的错误是:

connect. Timeout = -1

java.net.ConnectException: Connection refused: connect

这就是我得到的所有描述。我不确定如何解决这个问题。请帮忙。

4

1 回答 1

1

查看此页面以获取如何发送电子邮件的示例。您应该使用类 Transport 来发送电子邮件。

public static void send(String smtpServer, String to, String from
   , String subject, String body) throws Exception
  {

      Properties props = System.getProperties();
      // -- Attaching to default Session, or we could start a new one --
      props.put("mail.smtp.host", smtpServer);
      Session session = Session.getDefaultInstance(props, null);
      // -- Create a new message --
      Message msg = new MimeMessage(session);
      // -- Set the FROM and TO fields --
      msg.setFrom(new InternetAddress(from));
      msg.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse(to, false));
      // -- We could include CC recipients too --
      // if (cc != null)
      // msg.setRecipients(Message.RecipientType.CC
      // ,InternetAddress.parse(cc, false));
      // -- Set the subject and body text --
      msg.setSubject(subject);
      msg.setText(body);
      // -- Set some other header information --
      msg.setHeader("X-Mailer", "LOTONtechEmail");
      msg.setSentDate(new Date());
      // -- Send the message --
      Transport.send(msg);
      System.out.println("Message sent OK.");
  }

编辑:

因为你的评论...

检查是否有人阻塞了 25 端口(防火墙、其他应用程序)

身份验证也可能是一个问题,你可以在这里找到一个很好的例子

props.put( "mail.smtp.auth", "true" );
Authenticator auth = new SMTPAuthenticator( "me@sender.net", "mypassword" );
于 2009-07-27T11:05:49.780 回答