在 JavaMail 中设置 SOCKS 代理需要一些额外的配置,因为 JavaMail 本身并不直接支持 SOCKS 代理。但是,你可以通过配置 Java 的 java.net.Socket 工厂来使用 SOCKS 代理。
以下是如何为 JavaMail 设置 SOCKS 代理的步骤:
import javax.mail.*;
import javax.mail.internet.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
public class JavaMailWithSocksProxy {
// 自定义 Transport,以便使用带SOCKS代理的Socket
public static class SocksTransport extends Transport {
private Transport delegate;
private final Proxy proxy;
public SocksTransport(Session session, URLName urlname, Proxy proxy) {
super(session, urlname);
this.proxy = proxy;
try {
delegate = session.getTransport(urlname);
} catch (NoSuchProviderException e) {
throw new RuntimeException("Failed to get Transport", e);
}
}
@Override
public void connect(String host, int port, String user, String password) throws MessagingException {
try {
Socket socket = new Socket(proxy);
socket.connect(new InetSocketAddress(host, port));
delegate.connect(host, port, user, password);
} catch (IOException e) {
throw new MessagingException("Failed to connect via SOCKS proxy", e);
}
}
// 重写其他必要的方法以委托给delegate,或根据需求实现...
}
public static void main(String[] args) {
// 设置SOCKS代理信息
String proxyHost = "socks-proxy.example.com";
int proxyPort = 1080;
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));
// 创建JavaMail会话
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
try {
// 动态注册自定义的Transport
session.setProtocolForAddress("smtp", SocksTransport.class.getName());
// 使用自定义的Transport发送邮件
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient@example.com"));
message.setSubject("Test mail with SOCKS proxy");
message.setText("This is a test mail sent using JavaMail with SOCKS proxy.");
Transport.send(message);
System.out.println("Mail sent successfully.");
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。