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

Java Mail调用Gmail SMTP 587端口发送邮件时出现连接超时问题

Fixing SMTP Connection Timeout with Gmail in Java Mail API

Hey there, I’ve dealt with this exact timeout issue a few times when working with Gmail’s SMTP server—let’s walk through the most likely fixes step by step:

1. First, Rule Out Network/Firewall Issues

The "Operation timed out" error usually means your machine can’t reach smtp.gmail.com:587 at all. Let’s verify that first:

  • Run a quick connectivity test using telnet or nc (netcat) in your terminal:
    telnet smtp.gmail.com 587
    # Or if telnet isn't installed:
    nc -zv smtp.gmail.com 587
    
  • If the test fails, check:
    • Your local firewall (Windows Defender Firewall, macOS Firewall, etc.)—make sure it’s not blocking outbound connections on port 587.
    • Your company/school network—many organizations block SMTP ports to prevent spam. You might need to ask your network admin for exceptions, or try port 465 (SSL) instead.
    • Your ISP—some ISPs restrict SMTP ports; switching to port 465 could work here too.

2. Fix Gmail’s Security Settings (Critical!)

Gmail no longer allows regular passwords for third-party apps like Java Mail unless you use an App Password:

  • First, enable 2-Step Verification on your Google Account (you can find this under "Security" in your Google Account settings).
  • Once 2-Step Verification is on, go to the "App Passwords" section (still under Security). Generate a 16-character app password specifically for your Java Mail program.
  • Replace the PASSWORD value in your code with this app password—your regular Gmail password won’t work here anymore.

3. Make Sure Your Java Code Has the Required SMTP Properties

Looking at your code snippet, you’re missing two critical properties that Gmail’s SMTP server requires:

// Add these to your properties setup
properties.put("mail.smtp.auth", "true"); // Enables SMTP authentication
properties.put("mail.smtp.starttls.enable", "true"); // Required for port 587 (STARTTLS encryption)
  • If you switch to port 465 (SSL), replace the STARTTLS line with:
    properties.put("mail.smtp.ssl.enable", "true");
    
  • Also, it’s safer to use an integer for the port instead of a string—change String PORT = "587"; to int PORT = 587; and update the property to use the integer value.

4. Check for Proxy Issues

If you’re behind a corporate proxy, you’ll need to add proxy settings to your properties:

properties.put("mail.smtp.proxy.host", "your-proxy-server");
properties.put("mail.smtp.proxy.port", "your-proxy-port");
// If your proxy requires authentication:
properties.put("mail.smtp.proxy.user", "proxy-username");
properties.put("mail.smtp.proxy.password", "proxy-password");

Test with a Minimal Working Code

Here’s a complete, stripped-down example you can use to test if the connection works:

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

public class GmailTest {
    public static void main(String[] args) {
        String host = "smtp.gmail.com";
        int port = 587;
        String username = "myname@gmail.com";
        String appPassword = "your-generated-app-password"; // Use your App Password here

        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        // Create session with authentication
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, appPassword);
            }
        });

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("your-test-email@example.com"));
            msg.setSubject("SMTP Connection Test");
            msg.setText("If you get this, the connection works!");

            Transport.send(msg);
            System.out.println("Mail sent successfully!");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Start with the network test first—if that’s failing, none of the code fixes will help. Once connectivity is confirmed, work through the security settings and code adjustments.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:38:40