2013-03-16 128 views
3

我試圖使用以下方法我的程序發送電子郵件凍結:JVM嘗試發送電子郵件

void sendEmails(Tutor t, Date date, Time time, String tuteeName, String tuteeEmail){ 
    System.out.println("sending emails"); 
    Properties props = new Properties(); 
    props.put("mail.smtp.auth", "true"); 
    props.put("mail.smtp.starttls.enable", "true"); 
    props.put("mail.smtp.host", "smtp.gmail.com"); 
    props.put("mail.smtp.port", "465"); 

      SimpleDateFormat timeFmt = new SimpleDateFormat("hh:mm a"); 
      SimpleDateFormat dateFmt = new SimpleDateFormat("EEE, MMMM dd");   
      String datePrint = dateFmt.format(date); 
      String timePrint = timeFmt.format(time);     
      Session session = Session.getInstance(props, 
     new javax.mail.Authenticator() { 
        @Override 
     protected PasswordAuthentication getPasswordAuthentication() { 
      return new PasswordAuthentication(username, password); 
     } 
     }); 

      try { 

     Message tutorMessage = new MimeMessage(session); 

     tutorMessage.setFrom(new InternetAddress("[email protected]")); 

     tutorMessage.setRecipients(Message.RecipientType.TO, 
      InternetAddress.parse(t.getEmail())); 

     tutorMessage.setSubject("Tutoring Appointment Scheduled"); 
     tutorMessage.setText("Hey " + t.getName() + 
          "\n \t You have a new appointment scheduled on " + datePrint + " at " + timePrint + 
          "with " + tuteeName + ". \n If you cannot make this appointment, please contact club leadership immediately. " 
          + "\n Thanks for helping out!"); 

     Transport.send(tutorMessage); 

     System.out.println("Done sending"); 

    } catch (MessagingException e) { 
        System.out.println("messagingerror"); 
        e.printStackTrace(); 
    } 
} 

但是當程序運行到這個方法中,GUI鎖死和程序凍結。這是我第一次嘗試在一個Java程序中使用電子郵件,所以我不確定這是什麼東西。

+0

我懷疑它無法連接到SMTP服務器。請檢查服務器是否啓動。 – 2013-03-16 03:58:18

回答

1

你最好避免同步發送電子郵件。

通常會減慢應用程序的工作速度,更糟糕的是,它可能會凍結它,例如,如果郵件服務器無法訪問或不響應。

使用一些異步機制。

我相信在這種情況下,你的郵件服務器有問題。

使用一些獨立的Java程序來確保您可以使用這些服務器參數發送郵件。

+0

應該有一些設置超時的方式來運輸 – BlackJoker 2013-03-16 05:57:04

+0

當然。這是防止永久凍結的唯一方法。 – 2013-03-16 05:57:56

0

發現:465是通過SSL使用gmail發送電子郵件時使用的正確端口。但是,使用TLS時,正確的端口是587.

0

如果您從GUI中的事件處理程序調用此方法,則只要函數尚未完成,就會有效地阻止Swing Worker線程。每個GUI處理都是在Swing的一個線程中完成的(或者在SWT中),所以當你阻塞線程時,GUI不能被更新,即它會凍結。

您不應該在GUI線程中運行長時間運行的作業。相反,你應該創建一個新的線程並從中調用你的函數。

相關問題