Java邮件 : How to use different SOCKS5 for different threads?

标签 java multithreading jakarta-mail socks

我编写了多线程应用程序,它从每个线程的数据库连接到一些电子邮件帐户。 我知道 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/

相关文章:

msgpack-java 的 Javassist 运行时错误

java - JPA 选择不同计数

ios - 在大类上解析 countObjectsInBackground

android - Android 的 runOnUiThread() 方法

c - 使用 POSIX QUEUE 完成后该怎么做

java - TestNG 中的数据提供者

java - 带有日期作为 x 标签的 JFreeChart

java - 如何在java中搜索文件名并附加到邮件

java - 使用 Java Mail 下载附件

Javamail ISO-8859-1 格式