JavaMail:如何对不同的线程使用不同的SOCKS5? [英] JavaMail: How to use different SOCKS5 for different threads?
问题描述
我编写了一个多线程应用程序,该应用程序每个线程都从数据库连接到一些电子邮件帐户. 我知道JavaMail没有使用SOCKS5进行连接的任何选项,因此我决定通过System.setProperty方法使用它.但是此方法为整个应用程序设置了SOCKS5,我需要每个线程使用一个SOCKS5.我的意思是:
I wrote multithreading application which connects to some email accounts from database per thread. I know that JavaMail have no any options to use SOCKS5 for connection so I decided to use it via System.setProperty method. But this method sets SOCKS5 for whole application and I need to use one SOCKS5 per thread. I mean:
- 第一个线程:对bob @ localhost使用SOCKS 192.168.0.1:12345 连接
- 第二个线程:将SOCKS 192.168.0.20:12312用于 alice @ localhost连接
- 第三线程:使用SOCKS 192.168.12.:8080 for andrew @ localdomain进行连接
- first thread: uses SOCKS 192.168.0.1:12345 for bob@localhost to connect
- second thread: uses SOCKS 192.168.0.20:12312 for alice@localhost to connect
- third thread: uses SOCKS 192.168.12.:8080 for andrew@localdomain to connect
,依此类推.你能告诉我怎么做吗?
and so on. Can you tell me how to do this?
推荐答案
您需要使用所需的代理创建自己的套接字:
You need to create your own socket using the Proxy you want:
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()
方法:
The tricky bit is if you need authentication with the SMTP server to send mail. If that's the case, you have to create a subclass of javax.mail.Authenticator
and pass it to the Session.getInstance()
method:
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);
身份验证器的外观如下:
Where the authenticator looks like:
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;
}
}
这都是未经测试的,但是我相信这是您必须做的所有事情.它至少应该使您走上正确的道路.
This is all untested, but I believe it's everything you have to do. It should at least put you on the right path.
这篇关于JavaMail:如何对不同的线程使用不同的SOCKS5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!