我在使用 Java 向 Zimbra 邮件服务器发送电子邮件时遇到 RuntimeException 问题。
这是我的 Java
类 Test.java
public class Test {
public static void main(String[] args) {
sendMail("receiver@domain.com","Test","Test Message",null);
}
public static Properties getMailProperties() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.bevmi.com");
props.put("mail.smtp.port", "587");
return props;
}
public static boolean sendMail(String to, String subject,String text,String cc) {
final String username = "user@domain.com;
final String password = "password";
Properties props = getMailProperties();
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSender(new InternetAddress("sender@domain.com"));
if ((cc!=null) && (!cc.isEmpty())) {
message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
}
message.setSubject(subject);
message.setText(text, "UTF-8", "html");
System.out.println("Sending Message to :" + to);
Transport.send(message);
System.out.println("Email Sent");
return true;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
而且我在“主”线程中得到了以下 RuntimeException 堆栈跟踪信息。
java.lang.RuntimeException:javax.mail.MessagingException:无法将套接字转换为 TLS;嵌套异常是:javax.net.ssl.SSLHandshakeException:sun.security.validator.ValidatorException:PKIX 路径构建失败:sun.security.provider.certpath.SunCertPathBuilderException:无法在 Test.sendMail(测试.java:57) 在 Test.main(Test.java:13)
最佳答案
你看了吗this ? 这可能是您的解决方案。您的设置似乎缺少某些内容。
在我给你的链接中,通过添加此代码行解决了同样的问题。
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
在这种情况下,不应包含 "smtp.gmail.com"
但 "smtp.benvi.com"
如果那是您的真实主机。
希望对您有所帮助。
关于Java 无法找到有效的证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44963707/