這是我用來發送電子郵件的代碼:javax.mail.MessagingException:無法連接到SMTP主機:smtp.gmail.com,端口:465;
@Override
public void sendEmail(String from, String to, String subject, String content) {
//we set the credentials
final String username = ConfigService.mailUserName;
final String password = ConfigService.mailPassword;
//we set the email properties
Properties props = new Properties();
props.put("mail.smtp.host", ConfigService.mailHost);
props.put("mail.smtp.socketFactory.port", ConfigService.mailSmtpSocketPort);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.port", ConfigService.mailSmtpPort);
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));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(content);
Transport.send(message);
LOG.info(" Email has been sent");
} catch (MessagingException e) {
LOG.error(" Email can not been sent");
e.printStackTrace();
}
}
當我運行此我得到一個錯誤:
javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
我見過another question與此相關的一個位置,但有在這個問題上沒有被接受的答案。我可以ping到smtp.gmail.com
,也可以使用憑證訪問Gmail帳戶。
這是在我的機器上運行。
任何想法可能是什麼問題?
可能重複的[無法連接到SMTP主機:smtp.gmail.com,端口:465,響應:-1](http://stackoverflow.com/questions/15378133/could-not-connect-to- smtp-host-smtp-gmail-com-port-465-response-1) – bummi
這不是重複的,因爲在你提到的問題中沒有答案能解決我的問題。無論如何,感謝您的鏈接 – ftrujillo