[我正在尝试从Java应用程序从Windows Server 2016的Gmail帐户发送电子邮件,但出现错误:“无法连接到SMTP主机:smtp.gmail.com,端口:587。”
[在运行Windows 10的本地计算机上尝试时,代码运行完美。我已经使用了邮件启用功能,并且启用了端口587,并且还用作侦听SMTP的备用端口。另外,我在Windows服务器上为此端口配置了入站规则。我仍然有同样的错误。有人知道我能做什么吗?
我还将添加代码。
package email;
import java.sql.Timestamp;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class GoogleMail {
public void sendEmail(String emailContent) {
final String username = "[email protected]";
final String password = "*********";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("[email protected]"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("[email protected]"));
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
message.setSubject("Application Failed at" + timestamp);
message.setText(emailContent);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
该Gmail帐户是否已配置为允许“不安全的应用程序”?您可能需要设置一个应用令牌,以允许与gmail的此类直接连接。