[英]How to solve the issue with: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;?
[英]javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 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:无法连接到 SMTP 主机:smtp.gmail.com,端口:465;
嵌套异常是:
java.net.ConnectException:连接被拒绝
在 com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
在 com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
我在这里看到了与此相关的另一个问题,但该问题没有公认的答案。 我可以 ping 到smtp.gmail.com
,也可以使用凭据访问 gmail 帐户。
这是在我的机器上运行的。
知道可能是什么问题吗?
我在使用 NetBeans 进行调试时遇到了这个问题,甚至执行了实际的 jar 文件。 防病毒软件会阻止发送电子邮件。 您应该在调试期间暂时禁用防病毒软件,或者将 NetBeans 和实际的 jar 文件排除在扫描范围之外。 就我而言,我使用的是 Avast。
请参阅此链接以了解如何排除:如何将文件/网站异常添加到 avast! 杀毒软件 2014
这个对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.