簡體   English   中英

嘗試使用 smtp 服務器從 java 發送郵件時出現此錯誤! 如何解決這個問題

[英]Getting this error while trying to send mail using smtp server from java! how to solve this

所以我正在嘗試使用 Gmail smtp 端口 465 通過郵件發送 pdf 但它一直在拋出此錯誤,用谷歌搜索但無法解決此問題。

我不明白怎么了? 幫我這個?

提前致謝

試過:

1.更改端口

2.試圖更正證書上的某些內容無效

錯誤:

Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Exception reading response;
  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
    at com.sample.pdf.PDFMailing.pdfMail(PDFMailing.java:72)
    at com.sample.pdf.GeneratePdf.addDataToPdf(GeneratePdf.java:42)
    at com.sample.pdf.Report.main(Report.java:47)

PDFMailing.java

public static void pdfMail(String file){
        //Sender email-ID and Password.
                final String senderEmail="xxxxxx";//Sender Mail ID
                final String password="xxxxx";//Sender Mail ID Password.                
                //setting the Properties.
                Properties props=new Properties();
                props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
                props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
                props.put("mail.smtp.socketFactory.class",
                        "javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
                props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
                props.put("mail.smtp.port", "465"); //SMTP Port

                //Authenticating the mailID of the sender.
                    Authenticator auth = new Authenticator() {
                        //override the getPasswordAuthentication method
                        protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                            return new javax.mail.PasswordAuthentication(senderEmail, password);
                        }
                    };

                    //Creating and getting the Session Object.
                 Session session=Session.getInstance(props, auth);

                 //Setting the From, To, Subject, MessageBody. 
                 try{
                     Message message=new MimeMessage(session);
                     message.setFrom(new InternetAddress(senderEmail));//Sender Mail ID
                     message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("harshapirate@gmail.com"));//Receiver Mail ID
                     message.setSubject("Sample ECO PDF file");
                     message.setText("This a Sample ECO PDF file.");

                     MimeBodyPart bodyPart=new MimeBodyPart();
                      Multipart multipart=new MimeMultipart();

                      bodyPart.setText("This is multipart Text.");


                      //Attachments for any file.
                    MimeBodyPart pdfAttachment=new MimeBodyPart();
                    pdfAttachment.attachFile(file);

                    //Attach the Body part to the Multipart.
                    multipart.addBodyPart(bodyPart);
                    multipart.addBodyPart(pdfAttachment);

                    //Associate multipart to the message.
                    message.setContent(multipart);

                      System.out.println("Sending mail is in process.......");

                      //sending the message to-address mail.
                     Transport.send(message);
                     System.out.println("Mail has been sent sucessfully.");
                 }
                 catch(Exception e){
                     throw new RuntimeException(e);

                 }
    }

我假設是 Java 8.0.251。 由於您擁有最新的 Java 8 版本,因此不應發生這種情況:

  • 8.0.251 密鑰庫中的根證書應該都是最新的。
  • 真正的 smtp.google.com 應該是使用知名的根證書。
  • 真正的 smtp.google.com 不會以錯誤的順序呈現證書鏈。

所以我認為還有其他事情在“妨礙”。 可能的解釋包括:

  • 通過 SMTP 代理發送傳出 email 連接的東西; 例如防火牆或防病毒產品。

  • 您正在運行的應用程序服務器覆蓋了 JDK 提供的可信證書集。

也有可能是某些東西破壞了您的 DNS 或 IP 路由,並且您正在與欺騙性的“smtp.gmail.com”服務器通信。

檢查以下內容:

  • 檢查是否安裝了最新的 JDK(命令:java -version),以便它具有最新的證書和更新的 CA。

  • 檢查是否安裝了多個 JDK 或 JRE:如果是,請移除它們。

  • 檢查 JAVA_HOME 是否指向您安裝的最新 JDK。 (命令:echo $JAVA_HOME in linux 或 echo %JAVA_HOME% in Windows 命令提示符)

  • 檢查您的系統日期和時間是否正確。

如果驗證了以上內容,那么您的 Java 安裝就可以了。

代碼:

  • 我在您的代碼中看到一個缺失的屬性:props.put("mail.smtp.starttls.enable", "true")。 添加它並嘗試。

希望您至少能夠從瀏覽器訪問 Gmail。 這確認您的機器能夠訪問 Gmail 服務器 - 雖然不是對 SMTP 的精確測試,但測試仍然很好。

如果您在 Tomcat 中運行,請確保您擁有最新版本,並希望它的證書庫未以某種方式定制或更改。

如果以上一切正常,那么要么你在某個代理后面,要么你被黑了。

也許檢查系統屬性或其他人定義不同信任存儲的方式,例如:-Djavax.net.ssl.trustStore=somefilename.jks

請參閱: https://www.baeldung.com/java-keystore-truststore-difference

但是默認的信任庫應該是 $JAVA_HOME/jre/lib/security/cacerts(但它的內容在 Oracle JDK 和 OpenJDK 之間有所不同 - 后來修復了,參見: https://openjdk.java.net/jeps/319

檢查/修改商店的內容可以使用命令行工具完成:keytool 或 GUI,如: https://keystore-explorer.org/

在你 go 瘋狂嘗試啟動你的應用程序時,為 java (-Dsystempropertyname=value) 使用以下額外的系統屬性:

-Djavax.net.debug=all

然后,您將准確地看到所使用的信任庫的所有詳細信息和服務器提供的證書、SSL/TLS 握手的詳細信息,甚至是所有加密/解密的數據。

有關此主題的所有信息,請參閱 Java 版本的 JSSE 參考指南,例如: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html

所以我正在嘗試使用 Gmail smtp 端口 465 通過郵件發送 pdf 但它不斷拋出此錯誤,谷歌搜索但無法解決此問題。

我不明白怎么了? 幫我解決這個問題?

提前致謝

試過:

1.更換端口

2.試圖更正證書上的某些內容不起作用

錯誤:

Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Exception reading response;
  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
    at com.sample.pdf.PDFMailing.pdfMail(PDFMailing.java:72)
    at com.sample.pdf.GeneratePdf.addDataToPdf(GeneratePdf.java:42)
    at com.sample.pdf.Report.main(Report.java:47)

PDFMailing.java

public static void pdfMail(String file){
        //Sender email-ID and Password.
                final String senderEmail="xxxxxx";//Sender Mail ID
                final String password="xxxxx";//Sender Mail ID Password.                
                //setting the Properties.
                Properties props=new Properties();
                props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
                props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
                props.put("mail.smtp.socketFactory.class",
                        "javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
                props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
                props.put("mail.smtp.port", "465"); //SMTP Port

                //Authenticating the mailID of the sender.
                    Authenticator auth = new Authenticator() {
                        //override the getPasswordAuthentication method
                        protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                            return new javax.mail.PasswordAuthentication(senderEmail, password);
                        }
                    };

                    //Creating and getting the Session Object.
                 Session session=Session.getInstance(props, auth);

                 //Setting the From, To, Subject, MessageBody. 
                 try{
                     Message message=new MimeMessage(session);
                     message.setFrom(new InternetAddress(senderEmail));//Sender Mail ID
                     message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("harshapirate@gmail.com"));//Receiver Mail ID
                     message.setSubject("Sample ECO PDF file");
                     message.setText("This a Sample ECO PDF file.");

                     MimeBodyPart bodyPart=new MimeBodyPart();
                      Multipart multipart=new MimeMultipart();

                      bodyPart.setText("This is multipart Text.");


                      //Attachments for any file.
                    MimeBodyPart pdfAttachment=new MimeBodyPart();
                    pdfAttachment.attachFile(file);

                    //Attach the Body part to the Multipart.
                    multipart.addBodyPart(bodyPart);
                    multipart.addBodyPart(pdfAttachment);

                    //Associate multipart to the message.
                    message.setContent(multipart);

                      System.out.println("Sending mail is in process.......");

                      //sending the message to-address mail.
                     Transport.send(message);
                     System.out.println("Mail has been sent sucessfully.");
                 }
                 catch(Exception e){
                     throw new RuntimeException(e);

                 }
    }

相同類型的代碼,我之前寫過並且正在工作 state。請您嘗試使用下面的代碼:

此外,檢查系統中安裝的 8+ Java 的正確版本,以及正確設置和項目所需的所有環境變量。 如果您的系統中存在任何代理設置,請嘗試將其刪除,然后再次運行代碼。

//this will work only for gmail.

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

import com.[MyProjectRelatedImports].pojo.EmployeeDetails; 

public class SendEmail {
    public static void sendMail(List<EmployeeDetails> emplDetails) {

        Address[] to = new Address[emplDetails.size()];
        try {
            for (int i = 0; i < to.length; i++) {
                to[i] = new InternetAddress(emplDetails.get(i).getEmail());
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }

        // Recipient's email ID needs to be mentioned.
        String tom = "xyz@gmail.com";// address of recipient

        // Sender's email ID needs to be mentioned
        String from = "abc@gmail.com"; //address of sender
// Assuming you are sending email from localhost
        String host = "smtp.gmail.com";

        // Get system properties
        Properties properties = System.getProperties();

        // Setup mail server
    properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.user", "emailID"); // User name
        properties.put("mail.smtp.password", "password"); // password
        properties.put("mail.smtp.port", "587");// default mail submission port
        properties.put("mail.smtp.auth", "true");
        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("emailID", "password"); // username will be your email address and password same as your Gmail account.
// And if your account is protected with 2 step verification then you need to generate the app password from the link provided
//https://security.google.com/settings/security/apppasswords
            }
        });

        try {
            // Create a default MimeMessage object.
            MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
            message.setFrom(new InternetAddress(from));
// Set To: header field of the header.      //message.addRecipient(Message.RecipientType.TO, new InternetAddress(tom));
//Send Email to multiple recipients
            message.addRecipients(Message.RecipientType.TO, to);
// Set Subject: header field
            message.setSubject("Subject text via Java Class");
            // Now set the actual message
            message.setText("Message Content should be written here!!! Regards: Pratishtha Sharma ");
            // Send message
            Transport.send(message);
            System.out.println("Sent message successfully....");
        } catch (MessagingException mEx){
            mEx.printStackTrace();}
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM