我会立即说尝试连接时存在身份验证问题。您无需提供任何用户名或密码,除非您的交换服务器不需要用户名和密码。
更新:如果使用 JDK 7,请参阅以下帖子,它解决了此问题:
缺陷 - 使用 VPN 时 JDK7 权限被套接字拒绝 http://www.java.net/node/703177
“进一步挖掘,VPN 客户端似乎禁用了 IPv6,这导致 JDK7 出现问题。如果我使用以下标志 -Djava.net.preferIPv4Stack=true,我将不再看到错误。这是预期的解决方法还是这是一个问题?”
public class MailTest {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws MessagingException {
String host = "smtp.gmail.com";
String to = "[email protected] /cdn-cgi/l/email-protection";
String from = "[email protected] /cdn-cgi/l/email-protection";
String subject = "test";
String messageText = "body test";
Properties props = System.getProperties();
props.put("mail.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.port", "25");
// If using authentication, otherwise comment out
props.put("mail.smtp.auth", "true");
// Gmail requires TLS, your server may not
props.put("mail.smtp.starttls.enable", "true");
Session mailSession = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(messageText);
Transport transport = mailSession.getTransport("smtp");
//connect with authentication
//transport.connect(host,"myUsername" , "myPassword");
//connect without authentication
transport.connect();
transport.sendMessage(msg, address);
transport.close();
System.out.println("Mail was sent to " + to);
System.out.println(" from " + from);
System.out.println(" using host " + host + ".");
}
}