用java发送电子邮件
我添加了activation-1.1.jar和mail-1.4.jar 我还将电子邮件id设置更改为*允许不太安全的应用程序:ON 但我有以下例外用java发送电子邮件,java,email,servlets,Java,Email,Servlets,我添加了activation-1.1.jar和mail-1.4.jar 我还将电子邮件id设置更改为*允许不太安全的应用程序:ON 但我有以下例外 import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.mail.internet.MimeMessage; public class EmailSend { public static void main(String args
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);
}
}
}
我使用的是EclipseIDE3A您面临的错误与Java邮件无关,而是与SSL证书有关。要解决此错误,您需要将SMTP主机的证书导入密钥库 Google提供以下机制下载smtp证书:
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
请参阅其他方法下载上的证书
持有证书后,可以使用以下命令将证书导入java密钥库:
openssl s_client -starttls smtp -connect [hostname]:25 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'
希望这有帮助 我不知道这是否是正确的标记为副本,因为它鼓励OP绕过证书,假设他们已经尝试导入证书,而事实上他们可能只是不知道他们本来应该导入证书
keytool -import -file smtpgooglecert.cer -alias smtpgooglecert -keystore keystore.jks