您需要使用所需的代理创建自己的套接字:
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;
}
}
这一切都未经测试,但我相信这是你必须做的一切。它至少应该让你走上正确的道路。