gpt4 book ai didi

java - 用java发送电子邮件

转载 作者:行者123 更新时间:2023-12-02 11:19:46 26 4
gpt4 key购买 nike

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.internet.MimeMessage;
public class EmailSend {

public static void main(String args[]){
try{
String host ="smtp.gmail.com" ;
final String user = "abc@gmail.com";
final String pass = "password";
String to = "xyz@gmail.com";
String from = "abc@gmail.com";
String subject = "Trial";
String messageText = "Your Is Test Email :";
boolean sessionDebug = false;
Properties props = System.getProperties();

props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.required", "true");

java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(sessionDebug);
Message msg = new MimeMessage(mailSession);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(subject); msg.setSentDate(new Date());
msg.setText(messageText);

Transport transport=mailSession.getTransport("smtp");
transport.connect(host, user, pass);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
System.out.println("message send successfully");
}catch(Exception ex)
{
System.out.println(ex);
}

}
}

我添加了activation-1.1.1.jar 和mail-1.4.jar我还将电子邮件 ID 设置更改为 * 允许安全性较低的应用程序:开

但是我得到以下异常

javax.mail.MessagingException: Can't send command to SMTP host;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

我使用的是 eclipse IDE (oxygen 3A)

最佳答案

您遇到的错误与 Java 邮件无关,而是与 SSL 证书有关。要解决此错误,您需要将 SMTP 主机的证书导入到 keystore 中。

Google 提供以下机制来下载 smtp 证书:

openssl s_client -starttls smtp -connect [hostname]:25 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

请引用“https://support.google.com/a/answer/6180220?hl=en”上其他证书下载方法

拿到证书后,您可以使用以下命令将证书导入到您的 java keystore 中:

keytool -import -file smtpgooglecert.cer -alias smtpgooglecert -keystore keystore.jks

希望这有帮助!!

关于java - 用java发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50020135/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com