JVM在尝试发送电子邮件时冻结

时间:2013-03-16 03:54:26

标签: java email

我正在尝试使用以下方法从我的程序发送电子邮件:

    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("laneycodingclub@gmail.com"));

        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程序中使用电子邮件,所以我不确定阻止的位置。

3 个答案:

答案 0 :(得分:1)

您最好避免同步发送电子邮件。

通常它会降低应用程序的工作速度,更糟糕的是 - 它可能会冻结它,例如,如果邮件服务器无法访问或没有响应。

使用一些异步机制。

我确信在这种情况下您的邮件服务器有问题。

使用一些独立的Java程序来确保您可以使用这些服务器参数发送电子邮件。

答案 1 :(得分:0)

想出来:465是使用gmail通过SSL发送电子邮件时使用的正确端口。但是,使用TLS时,正确的端口是587。

答案 2 :(得分:0)

如果从GUI中的事件处理程序调用此方法,只要函数尚未完成,就会有效地阻止Swing Worker Thread。每个GUI处理都在Swing中的一个线程中完成(或者在SWT中完成),因此当您阻止线程时,GUI无法更新,即冻结。

您永远不应该在GUI线程中运行长时间运行的作业。相反,你应该创建一个新的Thread并从中调用你的函数。