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

时间:2017-02-04 08:19:10

标签: java email gmail javamail

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

这样的异常
  

邮件异常:无法连接到SMTP主机: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... :-)");

邮件功能第一次正常工作,但第二次调用时失败。

1 个答案:

答案 0 :(得分:0)

TLS通过加密通道提供身份验证,而不是安全性较低的清除通道

替换

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

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