首页 > 解决方案 > 如何修复'java.net.ConnectException:连接被拒绝:连接'

问题描述

我正在尝试通过我的网站(JSF 网站)发送一封电子邮件,该网站部署在 apache 服务器上,我不断收到“拒绝连接:连接”,但如果我直接从 NetBeans 运行 Java 应用程序中的代码,则代码可以完美运行. 对不起,如果我在帖子中犯了一些错误,你可以说这是我第一次发帖。:)

    public void sendReplicationCheckResult() {
    String to = "JcbSupportingSystem@jcbank.com.jo";

    // Sender's email ID needs to be mentioned
    String from = "Palestine.IT@jcbank.com.jo";

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

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

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.put("mail.smtp.auth", "false");
    properties.setProperty("mail.smtp.port", "25");

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

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // 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("Replication Check Results");

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(message, "text/html");

        // Create a multipart message
        Multipart multipart = new MimeMultipart();

        // Set text message part
    multipart.addBodyPart(messageBodyPart);
        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "C:\\Temp\\ReplicationCheck.pdf";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart);

        // Send message
        SMTPTransport t = (SMTPTransport) session.getTransport("smtp");

        // connect
        t.connect(new Socket(host, 25));

        // send
        t.sendMessage(message, message.getAllRecipients());

        System.out.println("Response: " + t.toString());

        t.close();
        Files.deleteIfExists(Paths.get("C:\\Temp\\ReplicationCheck.pdf"));
    } catch (MessagingException mex) {
        mex.printStackTrace();
    } catch (IOException ex) {
        Logger.getLogger(SendEmail.class.getName()).log(Level.SEVERE, null, ex);
    }
}

标签: java

解决方案


192.168.52.95是一个局域网地址。虽然在您的开发环境中,它可能有一个邮件服务器在等待,但在您的服务器环境中,192.168.52.95.

您可能想从属性文件中读取主机,这样您就可以在不同的环境中使用不同的主机。


推荐阅读