You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java自动发邮件程序连接localhost 25端口被拒绝,求解决方法

Java自动发邮件程序连接失败的问题排查与解决

你遇到的这个MailConnectException错误,核心原因是你的本地电脑(127.0.0.1)的25端口上没有运行SMTP邮件服务器,所以程序尝试连接时被系统直接拒绝了。咱们一步步拆解问题和解决方法:

你遇到的错误信息

com.sun.mail.util.MailConnectException: Couldn't connect to host, port: 127.0.0.1, 25; timeout -1;
nested exception is: java.net.ConnectException: Connection refused: connect
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2209)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:740)
    at javax.mail.Service.connect(Service.java:366)
    at javax.mail.Service.connect(Service.java:246)
    at javax.mail.Service.connect(Service.java:195)
    at javax.mail.Transport.send0(Transport.java:254)
    at javax.mail.Transport.send(Transport.java:124)
    at server.main(server.java:46)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.base/java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.base/java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
    at java.base/java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:400)
    at java.base/java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:243)
    at java.base/java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:225)
    at java.base/java.net.PlainSocketImpl.connect(PlainSocketImpl.java:148)
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:402)
    at java.base/java.net.Socket.connect(Socket.java:591)
    at java.base/java.net.Socket.connect(Socket.java:540)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:353)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:239)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
    ... 7 more

你的原始代码

// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class server {
    public static void main(String [] args) {
        // Recipient's email ID needs to be mentioned.
        String to = "my other email properly written";

        // Sender's email ID needs to be mentioned
        String from = "my email properly written";

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

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

        // Setup mail server
        properties.setProperty("mail.smtp.host", host);

        // 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("This is the Subject Line!");

            // Now set the actual message
            message.setText("This is actual message");

            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

问题原因分析

咱们普通个人电脑默认是不会运行SMTP服务器的,127.0.0.1的25端口处于空闲状态,所以程序尝试连接时,系统会直接返回“连接拒绝”的错误。你以为用localhost就能发邮件,但实际上localhost只是指向自己的电脑,没有邮件服务的话根本没法处理邮件发送请求。

两种解决方法

方法1:使用第三方邮箱服务商的SMTP服务器(推荐,生产环境常用)

这是最快捷的方式,比如用QQ邮箱、Outlook邮箱或者Gmail的SMTP服务,步骤如下:

  1. 开启邮箱的SMTP服务:
    • 以QQ邮箱为例:登录QQ邮箱 → 设置 → 账户 → 找到“POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务” → 开启“SMTP服务”,然后获取授权码(不是你的邮箱登录密码)。
  2. 修改代码中的配置:
    需要添加SMTP认证、SSL/TLS加密的配置,替换host为服务商的SMTP地址,示例代码如下(以QQ邮箱为例):
// File Name SendEmail.java
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class server {
    public static void main(String [] args) {
        String to = "接收方邮箱@xxx.com";
        String from = "你的QQ邮箱@qq.com";
        // QQ邮箱的SMTP服务器地址
        String host = "smtp.qq.com";
        // 这里填你获取的SMTP授权码
        String authCode = "你的QQ邮箱授权码";

        Properties properties = System.getProperties();
        // 配置SMTP服务器地址
        properties.setProperty("mail.smtp.host", host);
        // 开启SMTP认证
        properties.put("mail.smtp.auth", "true");
        // 开启SSL加密(QQ邮箱用465端口)
        properties.put("mail.smtp.socketFactory.port", "465");
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.port", "465");

        // 创建带认证的Session
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, authCode);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("This is the Subject Line!");
            message.setText("This is actual message");

            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

注意:不同服务商的SMTP配置略有不同,比如Outlook的SMTP地址是smtp.office365.com,端口587,需要开启TLS加密;Gmail的SMTP地址是smtp.gmail.com,端口587。

方法2:搭建本地SMTP服务器(仅用于测试)

如果你只是想测试邮件发送逻辑,不想用真实邮箱,可以搭建一个本地的SMTP测试服务器,比如:

  • FakeSMTP:一个轻量的Java工具,启动后会在本地监听指定端口,接收邮件但不会真正发送出去,适合开发测试。
  • Postfix/Sendmail:Linux系统上的老牌SMTP服务,Windows可以用hMailServer。
    搭建完成后,把代码中的host改成本地服务器的地址,端口改成对应的监听端口即可。

内容的提问来源于stack exchange,提问作者wutBruh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:07:39