使用 JavaMail 库发送邮件在第二封邮件上显示异常

Sending mail using JavaMail library shows exception on second Mail

我正在尝试在用户单击按钮时发送邮件。但是,当我再次单击相同的按钮时,会出现

这样的异常

Mail Exception :Could not connect to SMTP host: smtp.gmail.com, port: 587

属性代码:

 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", "587");

留言代码:

session =
   Session.getDefaultInstance(
      props,
      new javax.mail.Authenticator() {
         protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication( 
               MailIntegrationFromAddress.getText().trim(),
               MailIntegrationFromAddressPassword.getText().trim()); // change accordingly  
   }});
try {
   message.setFrom( new InternetAddress( MailIntegrationFromAddress.getText()));
   message.addRecipient( Message.RecipientType.TO, new InternetAddress(to));
   message.setSubject("Subject type");
   BodyPart messageBodyPart = new MimeBodyPart();
   messageBodyPart.setText("Message Body");
   Multipart multipart = new MimeMultipart();
   multipart.addBodyPart(messageBodyPart);
   messageBodyPart = new MimeBodyPart();
   String filename = FileLocation.getText();
   DataSource source = new FileDataSource(filename);
   messageBodyPart.setDataHandler(new DataHandler(source));
   messageBodyPart.setFileName(filename);
   multipart.addBodyPart(messageBodyPart);
   message.setContent(multipart);
   message.saveChanges();
   setCursor(new Cursor(Cursor.WAIT_CURSOR));
   Transport.send(message);
   setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
   JOptionPane.showMessageDialog(null, "Mail sent Successfully... :-)");

邮件功能第一次正常,第二次调用失败

TLS 通过加密通道而不是 less-secure 透明通道

提供身份验证

替换

props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");

props.put("mail.smtp.starttls.enable", "true");