我正尝试将邮件发送到gmail,因为我的主机服务是免费的,但是stacktrace说
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 587;
虽然代码在我的Eclipse IDE上执行时工作正常。我问托管服务是否有任何防火墙可以阻止相同。但是他们否认了这一点,说你的ip在防火墙中没有被阻止,并且给定端口也在服务器上打开并且能够连接到远程服务器。那可能是问题的原因。这是代码
final String username = "xyz@gmail.com";
final String password = "abcd";
Properties properties = System.getProperties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication(username,
password);
}
});
out.print(session);
response.setContentType("text/html");
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("xyz@gmail.com"));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
"abc@gmail.com"));
message.setSubject("hello");
message.setText("this is me");
Transport.send(message);
} catch (MessagingException mex) {
out.print(mex);
}
}