无法从防火墙/代理后面发送电子邮件

问题描述 投票:0回答:0

我有一个应用程序在位于 secure 网络中的服务器上运行。该应用程序需要访问一些在线资源,这需要设置防火墙和代理设置。目前一切(HTTPS 和 SFTP)都在工作,除了发送电子邮件。

对于应用程序,我必须将其配置为使用 socks 代理和 HTTP 代理(均通过命令行选项设置)

-Dhttp.proxyHost=aaa.net
-Dhttp.proxyPort=8080
-Dhttp.nonProxyHosts="localhost|127.*|[::1]"
-DsocksProxyHost=socks5.aaa.net
-DsocksProxyPort=8081

在网络中,不需要代理来访问 SMTP 服务器,只需要为应用程序服务器提供防火墙访问权限即可访问 SMTP(通过 PowerShell 脚本成功测试,请参见下文)。

发送电子邮件的 java 代码目前如下所示:

properties.put("mail.smtp.auth", "false");
properties.put("mail.smtp.timeout", 5000); // I read somewhere in another post that increasing the timeout can help, but it didn't
properties.put("mail.smtp.starttls.enable", "true"); // also tried "false"
//properties.put("mail.smtp.ssl.trust", host);
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
// I tested the above configuration first, before adding the following. The result was the same (it didn't work)
properties.put("mail.smtp.socks.host", "socks5.aaa.net");
properties.put("mail.smtp.socks.port", 8081);

MailSSLSocketFactory sf = new MailSSLSocketFactory(); // I've tested with and without this, the result seems to be the same
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.socketFactory", sf);

session = Session.getInstance(properties);

Message message = createAndFillMessage( .... ); // all the blah blah for the message

Transport.send(message);

以下错误是我在代码运行时得到的(网络实际上是可达的,见下文)

com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.aaa.net, 25; timeout -1; Using SOCKS host, port: socks5.aaa.net, 8081;
  nested exception is:
    java.net.SocketException: SOCKS: Network unreachable
    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)
Caused by: java.net.SocketException: SOCKS: Network unreachable
    at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:487)
    at java.base/java.net.Socket.connect(Socket.java:666)
    at java.base/java.net.Socket.connect(Socket.java:600)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:359)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:238)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:2175)
    ... 8 more

让我感到更加困惑的是,我已经通过一个简单的 PowerShell 脚本测试了 SMTP(从服务器)以使用

Send-MailMessage
发送电子邮件,对于 PowerShell 脚本,我不必输入任何代理详细信息,只需一个简单的文本连接,没有授权或任何特殊的东西,它只是工作......但是,到目前为止,我在 Java 应用程序中尝试的一切都失败了。

我怀疑问题在于我必须为 SFTP 连接配置 SOCKS 代理,现在它以某种方式干扰(应该是)一个简单的 SMTP 调用。

目前服务器上使用的是Java 19(OpenJDK 19)

java proxy smtp socks java-19
© www.soinside.com 2019 - 2024. All rights reserved.