2017-02-04 21 views
1

我想在用戶單擊按鈕時發送郵件。但是,當我點擊相同的再次發生異常喜歡使用JavaMail庫發送郵件會在第二個郵件中顯示異常

郵件異常:無法連接到SMTP主機:smtp.gmail.com端口: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... :-)"); 

的郵件功能工作正常第一次,但第二次調用失敗。

+0

郵更多的代碼,請。 – Aubin

+0

@Aubin,謝謝,我添加了完整的代碼。 –

+0

看來你重用了消息對象。這是一個好習慣嗎?嘗試實例化一條新消息。 – Aubin

回答

0

TLS提供認證通過加密信道,而不是一個安全性較低的無干擾信道

替換

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

props.put("mail.smtp.starttls.enable", "true"); 
相關問題