Domanda

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:

  • 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?

È stato utile?

Soluzione

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);

Then use it for the connection:

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

Edit: 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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top