无法使用JavaMail API发送电子邮件

时间:2014-04-26 18:38:13

标签: java javamail

我正在尝试使用Java Mail API发送一封简单的电子邮件,但其抛出错误如下所示

Exception in thread "main" javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client
        at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:765)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
        at javax.mail.Service.connect(Service.java:295)
        at javax.mail.Service.connect(Service.java:176)
        at JavaMail.main(JavaMail.java:50)

以下是我的代码

        Properties props = new Properties();
        //props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth.plain.disable", true);
        props.put("mail.smtp.host", "127.0.0.1");
        props.put("mail.smtp.port", "25");


        Transport transport = null;
//      Session session = Session.getInstance(props,
//        new javax.mail.Authenticator() {
//          protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
//              return new PasswordAuthentication(username, password);
//          }
//        });
// 

        Session session = Session.getDefaultInstance(props,null);
        session.setDebug(true);
        System.out.println(" session was created "+session.toString());
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("me@example.com"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("you@example.com"));
        message.setSubject("Testing Java EMail  Subject");
        message.setText("Dear Mail Crawler,"
            + "\n\n Test Email....!!! please!");


        transport = session.getTransport("smtp");
        transport.connect("127.0.0.1", "user", "pass");
        transport.sendMessage(message, message.getAllRecipients());

        System.out.println("email was SEnt sUcessfully ");

1 个答案:

答案 0 :(得分:2)

您需要取消注释并将此代码放在Session session = Session.getDefaultInstance(props,null); ...

之后
  session = Session.getInstance(props,
  new javax.mail.Authenticator() {
     protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(username, password);
      }
   });