在java中发送电子邮件

时间:2018-04-25 10:38:04

标签: java email servlets

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(氧气3A)

1 个答案:

答案 0 :(得分:1)

您遇到的错误与Java邮件无关,但与SSL证书无关。要解决此错误,您需要将SMTP主机的证书导入密钥库。

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密钥库:

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

希望这会有所帮助!!