使用Gmail SMTP的JavaMail无法发送消息

时间:2014-07-22 18:16:05

标签: java smtp gmail javamail

我想发送一封包含JavaMail的电子邮件,但每次我都会收到异常。我创建了一个JFrame项目,并为按钮创建了一个actionevent:

  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  Properties 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", "465");

  Session session = Session.getDefaultInstance(props,
          new javax.mail.Authenticator() {
              @Override
              protected PasswordAuthentication getPasswordAuthentication() {
                  return new PasswordAuthentication("xyz@gmail.com", "###");
              }
          }
  );
  //I've tried also this version of the Session:
  //Session session = Session.getInstance(props,new NewEmpty("xyz@gmail.com","###"));
  try {
      Message message = new MimeMessage(session);
      message.setFrom(new InternetAddress("xyz@gmail.com"));
      message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("zyx@gmail.com"));
      message.setSubject("Hi");
      message.setText("Helló!");

      Transport.send(message);
      JOptionPane.showMessageDialog(null, "Sent!");
  }catch(Exception e) {
      JOptionPane.showMessageDialog(null, e);
  }

}                                        

}

例外是:

Screenshot http://i62.tinypic.com/2ef70jl.jpg

1 个答案:

答案 0 :(得分:0)

您的屏幕截图显示了SSL握手错误。

您可能必须将其SSL证书或根证书导入您自己的java信任/密钥库。

我找到了这个部分的tutorial来描述单个步骤。