从其他设备运行时,java邮件程序无法正常工作

时间:2018-10-06 08:02:11

标签: java smtp

我已经检查了程序,代码在一个系统上运行,但是当我将该文件迁移到另一个系统上时,出现以下错误,我想知道为什么会这样以及如何解决此问题?我的凭据是正确的

package javaapplication6;  

import java.util.Properties;    
import javax.mail.*;
import javax.mail.internet.*;    
class Mailer{  
    public static void send(String from,String password,String to,String sub,String msg){  
          //Get properties object    

          Properties props = new Properties();    
          props.put("mail.smtp.host", "smtp.gmail.com");    
          props.put("mail.smtp.socketFactory.port", "465"); 
          props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
          props.put("mail.smtp.auth", "true");    
          props.put("mail.smtp.port", "465");
          //get Session
          Session session = Session.getDefaultInstance(props,    
           new javax.mail.Authenticator() {    
           protected PasswordAuthentication getPasswordAuthentication() {    
           return new PasswordAuthentication("XXXX@gmail.com","XXXXXXXXX");  
           }    
          });    
          //compose message    
          try {    
           MimeMessage message = new MimeMessage(session);    
           message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));    
           message.setSubject(sub);    
           message.setText(msg);    
           //send message  
           Transport.send(message);    
           System.out.println("message sent successfully");    
          } catch (MessagingException e) {throw new RuntimeException(e);}    

    }  
}  
public class SendEmail{    
 public static void main(String[] args) {    
     //from,password,to,subject,message  
     Mailer.send("XXXX@gmail.com","XXXXXXXXX","itkrishcommerce@gmail.com","hello javatpoint","How r u?");  
     //change from, password and to  
 }    
}

我得到的异常:

  

线程“ main”中的异常java.lang.RuntimeException:   javax.mail.MessagingException:无法连接到SMTP主机:   smtp.gmail.com,端口:465;

     

嵌套的异常是:javax.net.ssl.SSLHandshakeException:   sun.security.validator.ValidatorException:PKIX路径构建失败:   sun.security.provider.certpath.SunCertPathBuilderException:无法执行   找到到所请求目标的有效认证路径

     

在javaapplication6.Mailer.send(SendEmail.java:32)在   javaapplication6.SendEmail.main(SendEmail.java:39)

     

原因:javax.mail.MessagingException:无法连接到SMTP   主机:smtp.gmail.com,端口:465;嵌套的异常是:

     

javax.net.ssl.SSLHandshakeException:   sun.security.validator.ValidatorException:PKIX路径构建失败:   sun.security.provider.certpath.SunCertPathBuilderException:无法执行   找到到所请求目标的有效认证路径

1 个答案:

答案 0 :(得分:0)

这是由于Avast Antivirus阻止了端口,所以我将其卸载了,该程序运行正常!