javax.mail.AuthenticationFailedException:535 5.0.0身份验证失败

时间:2011-07-23 13:07:01

标签: java javamail hotmail

我不明白为什么我会得到这个例外。 这是尝试发送电子邮件的代码。

public void sendAsHotmail() {
    final String username = jTextField14.getText();
    final String password = jPasswordField4.getText();
    String subject = jTextField16.getText();
    String Cc = jTextField17.getText();
    String Bcc = jTextField18.getText();
    String recipient = jTextArea5.getText();

    Properties props = new Properties();
    props.put( "mail.smtp.host" , "smtp.live.com");
    props.put( "mail.smtp.user" , username );

    // Use TLS
    props.put("mail.smtp.auth" , "true" );
    props.put( "mail.smtp.starttls.enable" , "true" );
    props.put( "mail.smtp.password" , password );

    Session session = Session.getDefaultInstance( props , new Authenticator() {
        @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                  if( username == null | password == null ) 
                      JOptionPane.showMessageDialog( new JFrame() , "username or password incorrect");
                  return new PasswordAuthentication( username , password );
                }
    });
    String to = recipient;
    String from = username + "@hotmail.com";
    String emailMessage = jTextArea2.getText();
    MimeMessage message = new MimeMessage(session);
    MimeBodyPart attachment = new MimeBodyPart();
    MimeBodyPart messagePart = new MimeBodyPart();
    FileDataSource fds = new FileDataSource( fileName );

    try {
        message.setRecipients( Message.RecipientType.TO, InternetAddress.parse( to ) );
        message.setFrom( new InternetAddress(from) );
        message.setSubject(subject);
        message.setText( emailMessage );
        attachment.setDataHandler( new DataHandler( fds ) );
        attachment.setFileName( fileName );
        messagePart.setText( emailMessage );
        Multipart hotmailMP = new MimeMultipart();
        hotmailMP.addBodyPart(attachment);
        hotmailMP.addBodyPart( messagePart );
        message.setContent( hotmailMP );
        Transport transport = session.getTransport("smtp");
        transport.send(message);
        JOptionPane.showMessageDialog(new JFrame() , "mail sent !");       
    }  catch(Exception exc) {
        System.out.println(exc);
    }
}

为什么我会得到这个例外?如果代码有任何问题,请说明问题所在。

2 个答案:

答案 0 :(得分:5)

535表示用户名或密码错误:请参阅SMTP reply codes

您可能需要检查SMTP服务器手册以了解5.0.0的含义。

答案 1 :(得分:5)

我同意@ Mi Mee。 在您的用户名中,您似乎使用了不完整的用户名(这就是身份验证失败的原因)。对于Hotmail,您必须输入可能为xyz@hotmail.com , qrs@gmail.com 等的 Windows Live ID

所以请输入正确的用户名。并从@hotmail.com变量中删除from。其余的代码很好。