这是我用来发送电子邮件的代码:
@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,port:465;嵌套异常是:java.net.ConnectException:com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)在com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)处拒绝连接
我在这里看到了与此相关的another question,但在这个问题上没有被接受的答案 . 我可以ping到 smtp.gmail.com
并且我也可以使用凭据访问gmail帐户 .
这是在我的机器上运行的 .
知道可能是什么问题吗?
1 回答
我在使用NetBeans进行调试时遇到过这个问题,甚至执行实际的jar文件 . 防病毒软件会阻止发送电子邮件 . 您应该在调试期间暂时禁用防病毒软件,或者排除NetBeans并扫描实际的jar文件 . 就我而言,我正在使用Avast .
请参阅此链接,了解如何排除:How to Add File/Website Exception into avast! Antivirus 2014
这个对我有用 .