我编写了多线程应用程序,它从每个线程的数据库连接到一些电子邮件帐户。 我知道 JavaMail 没有任何选项可以使用 SOCKS5 进行连接,因此我决定通过 System.setProperty 方法使用它。但这种方法为整个应用程序设置了 SOCKS5,我需要每个线程使用一个 SOCKS5。我的意思是:
- 第一个线程:使用 SOCKS 192.168.0.1:12345 for bob@localhost 连接
- 第二个线程:使用 SOCKS 192.168.0.20:12312 alice@localhost 连接
- 第三个线程:使用 SOCKS 192.168.12.:8080 用于连接 andrew@localdomain
等等。你能告诉我该怎么做吗?
最佳答案
您需要使用所需的代理创建自己的套接字:
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);
validator 的样子:
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;
}
}
这一切都未经测试,但我相信这就是您必须做的一切。它至少应该让你走上正确的道路。
关于Java邮件 : How to use different SOCKS5 for different threads?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7540976/