1

我编写了多线程应用程序,它从每个线程的数据库连接到一些电子邮件帐户。我知道 JavaMail 没有任何选项可以使用 SOCKS5 进行连接,所以我决定通过 System.setProperty 方法使用它。但是这种方法为整个应用程序设置了 SOCKS5,我需要每个线程使用一个 SOCKS5。我是说:

  • 第一个线程:使用 SOCKS 192.168.0.1:12345 连接 bob@localhost
  • 第二个线程:使用 SOCKS 192.168.0.20:12312 连接 alice@localhost
  • 第三个线程:使用 SOCKS 192.168.12.:8080 为 andrew@localdomain 连接

等等。你能告诉我怎么做吗?

4

1 回答 1

2

您需要使用所需的代理创建自己的套接字:

SocketAddress addr = new InetSocketAddress("socks.mydomain.com", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
Socket socket = new Socket(proxy);
InetSocketAddress dest = new InetSocketAddress("smtp.foo.com", 25);
socket.connect(dest);

然后将其用于连接:

SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
transport.connect(socket);

编辑:棘手的一点是,如果您需要通过 SMTP 服务器进行身份验证才能发送邮件。如果是这种情况,您必须创建一个子类javax.mail.Authenticator并将其传递给该Session.getInstance()方法:

MyAuthenticator authenticator = new MyAuthenticator();

Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter",
                        authenticator.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");

Session session = Session.getInstance(properties, authenticator);

身份验证器的外观如下:

private class MyAuthenticator extends javax.mail.Authenticator 
{
    private PasswordAuthentication authentication;

    public Authenticator() 
    {
         String username = "auth-user";
         String password = "auth-password";
         authentication = new PasswordAuthentication(username, password);
    }

    protected PasswordAuthentication getPasswordAuthentication() 
    {
        return authentication;
    }
}

这一切都未经测试,但我相信这是你必须做的一切。它至少应该让你走上正确的道路。

于 2011-09-24T18:33:32.683 回答