我想编写一个使用 SMTP TLS 与 gmail 服务器连接的程序。我正在使用此页面上提到的代码:
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
我收到连接超时异常。如果我使用 SMTP SSL,我可以成功发送电子邮件。
public void sendUsingSMTP_TLS() {
final String username = "username@gmail.com";
final String password = "password";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "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("from-email@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to-email@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Dear Mail Crawler,"
+ "\n\n No spam to my email, please!");
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
我得到以下异常:
Exception in thread “main” java.lang.RuntimeException: javax.mail.MessagingException:
Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at SMTP_TLS.main(SMTP_TLS.java:48)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
at SMTP_TLS.main(SMTP_TLS.java:43)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:299)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
… 7 more